# Question
Title: How do I use a JBox2D ContactListener to check if my character is standing on the ground?
I want to know when my character is touching a wall or floor. I've had no luck searching for information on this. I saw a few things about `ContactListeners` and `getContactList()`, but I don't understand how to use them.

How can I do this?

# Answer
> 3 votes
I recently implemented a similar detection in a platformer using Box2D, to know if my player body was touching the ground (to allow the player to jump—or not). There are many ways to do it, but here is my way.

Give your character body two fixtures; a solid one and a sensor. (If you're unfamiliar with the concepts, read the relevant manual chapter.) Arrange them like this:

### Sensor

From the official manual:

> Sometimes game logic needs to know when two fixtures overlap yet there should be no collision response. This is done by using sensors. A sensor is a fixture that detects collision but does not produce a response.

Here, the *sensor* (in blue) will be used to detect if something is "under the feet" of the body and will lead to no collision response (it's a sensor). Collision responses are handled by the *solid fixture* (or *main fixture*; in red).

To manipulate fixtures through contact listeners, you need a way to know if a given fixture is actually the relevant one. A simple way to do this setting the fixture sensor's *user data* (you can set user data on both fixtures and bodies). Here, a simple integer should do the job:

```
feetSensor.setUserData(FEET_SENSOR_ID);

```

Later on in the listener, to check if a fixture is the sensor, you simply do:

```
if ((Integer) feetSensor.getUserData() == FEET_SENSOR_ID) {
    // This is the feet sensor
}

```

### Contact Listener

Since the sensor is at the bottom of the body, if there is at least one contact between it and any other fixture, you can safely assume that the body is "on the ground".

A contact listener is used to listen to contacts occurring in the world. Each time two fixtures contact each other (touch), the `beginContact` method is called with a `Contact` instance as parameter, containing data about the contact. From this `Contact` instance, you can use `getFixtureA()` and `getFixtureB()` methods to get the two fixtures involved in the contact:

```
Fixture fA = contact.getFixtureA()
Fixture fB = contact.getFixtureB()

```

Once you have the two fixtures, you need to check if this contact is relevant. In our scenario, a contact is relevant if one of the two fixtures is the feet sensor. This method returns whichever (or neither) of its arguments is the feet sensor:

```
private Fixture getFeetFixture(Fixture f1, Fixture f2) {
    if (f1.getUserData() != null && (Integer) f1.getUserData() == FEET_SENSOR_ID) {
        return f1;
    } else if (f2.getUserData() != null && (Integer) f2.getUserData() == FEET_SENSOR_ID) {
        return f2;
    }
    return null;
}

```

Then, each time you encounter a relevant contact in the `beginContact` method, you can, for example, increment a static counter variable to keep track of how many fixtures contact the feet sensor.

Finally, you still need to handle the case where two fixtures are no longer in contact. Use the `endContact` method just like you used `beginContact`. This method also receives a `Contact` instance as parameter. After checking whether the contact involves the feet sensor as before and finding it to be so, you **decrement** the static counter variable (reducing the number of fixtures the sensor is in contact with, by one).

You can then check if the counter variable is greater than zero to know whether the player character is on the ground.

Here's a complete implementation of such a contact listener:

```
public class FeetContactListener implements ContactListener {
    private static int nbFootContacts = 0;

    private Fixture getFeetFixture(Fixture f1, Fixture f2) {
        if (f1.getUserData() != null && (Integer) f1.getUserData() == FEET_SENSOR_ID) {
            return f1;
        } else if (f2.getUserData() != null && (Integer) f2.getUserData() == FEET_SENSOR_ID) {
            return f2;
        }
        return null;
    }

    @Override
    public void beginContact(Contact contact) {
        Fixture feetFixture;

        if ((feetFixture = getFeetFixture(contact.getFixtureA(),
            contact.getFixtureB())) != null) {
        nbFootContacts++;
        if (nbFootContacts > 0) {
                    //touching the ground
        }
    }

    @Override
    public void endContact(Contact contact) {
    Fixture feetFixture;

    if ((feetFixture = getFeetFixture(contact.getFixtureA(),
            contact.getFixtureB())) != null) {

        nbFootContacts--;
        if (nbFootContacts <= 0) {
                        //not touching the ground
        }
    }
}

```

The last step is to register the contact listener with the physics `World`.

```
world.setContactListener(new FeetContactListener());

```

I find this way quite flexible, since you can add as many fixtures as you want (and hence, as many sensors as you want). Add a sensor for parts of the body that need specific collision handling.

### Resources

# Answer
> 0 votes
```
public boolean collisionWith(String objectData) { // objectData is FixtureDef.userData (see below)
    ContactEdge e = body.getContactList(); // body is JBox.Body object
    while (e != null) {
        if (e.contact.m_fixtureA.getUserData() == objectData && e.contact.isTouching())
            return true;
        if (e.contact.m_fixtureB.getUserData() == objectData && e.contact.isTouching())
            return true;
        e = e.next;
    }
    return false;
}

```

This is not using ContactListener so you need to call this method. All you need to do is whenever you are creating Fixture for a body set userData to some String:

```
FixtureDef ballFixture = new FixtureDef();
ballFixture.userData = "Ball";

```

---
Tags: java, lwjgl, jbox2d
---


# Question
Title: Multiple Sprite animation layers overlayed in Unity Animator
I have an animator with two layers, an axe layer and a body layer.

I would like to animate the two in sync with each other. They are both 64x64 sprite animations, frame-by-frame bitmaps.

The problem I'm having is I can't figure out how to alpha blend the layers. The axe either plays and the player body becomes invisible, or the axe isn't visible.

I have a bunch of states like this which each return to an idle state. And link to an animation. I'd post a screenshot but I'm not allowed.

The axe layer is set to sync so the state machine looks the same, and I set the motion to the axe animations rather than the character body animations.

# Answer
Layers are usually used for 3D animations that share common avatar and masking them. You said they are sprite animations. In case of sprite animation, ax/prop animation is done with main animation sprites or separate object animation with separate animator.

If ax's animation is a sprite animation then you have to create an extra state of animation that has both body and ax animation sprite drawn combined.

If it's a transformation animation then you can put the ax as a child object of the body and animate in the animation tab with the same body animation. Ax sprite can easily be synced that way in whichever frame you want.

If it's a component(enable-disable) animation you can easily do it as same above. All child objects and most of their components are accessible from animation.

For syncing with two animator call the ax's methods from body's animation's `Animation Event`. If ax has some proposes in the game like it goes in and attacks all the enemies in the scene then you should do it this way. If it just damages opponent when in attack state then go with single animator ways as you need.
> 1 votes

# Answer
I know this is an old question, but I wanted to put in my two cents as well. Plus this QA is still popping up on Google. So... yeah.

Using Animation Layers with 2D Sprites is still useful. Just not in the way you the OP was trying. You might put the legs in layer1, the body in layer2, and the eyes in layer3. You'd have to re-implement the decision on which way the sprite is facing. But the legs could go walking while the arms are idle, or while the arms are swinging. Or the legs could be idle regardless of the arms state. And then the eyes could blink randomly regardless of whatever else you're doing.

So the whole purpose of those layers is trying to *desync* the animations.

I'm actually trying to look up the same thing as the OP so I can use layers from the LPC character creator to dynamically create characters. Demonstration and Sprite Sources

And I want to do this without going overboard on resources. I'm not entirely certain how I'll go about it, but here's an idea for it:

A script automatically generates and keeps track of children sprites. If there's a sprite object that it doesn't know about on the character, it will delete it when it updates the sprites on the object. There is one Animator Controller base. There will be like... 5 to 20 children sprites per character. Every sprite has an Animator Override Controller. The script that keeps track of the multiple sprites/controllers will iterate through the list to change/trigger parameters on all the controllers, based on one change/trigger given to the script.

I need to test how resource intensive this is. I also need to test how in-sync it is. If it's not in-sync enough, I'll need to add a reset trigger maybe...

In addition to that, I'm in the middle of writing an EditorScript to automatically process LPC animation textures, slice them into sprites, and animate them so they're all identical for any given selection of textures.

If the animations have slightly different timings though, the shared controller override idea would fail. The second option I'm looking at is making my own animator of sorts that just runs on a schedule and changes all the sprites based on an array passed in. But for some spritesheets (doesn't include a particular motion), it would require repacking, which I don't really want to do very much. So my auto-animator makes more sense than that...
> 0 votes

# Answer
This is an old question and so this answer is way overdue. The only reason I am posting this answer is because I came across this question while also trying to solve the same problem in Unity 2018.4. It may well turn out that this answer wouldn't have applied to the 2016 version of Unity anyway. But here goes.

The solution to this problem is create a hierarchy of game objects. In your case something like:

```
Lumberjack
   Body
   Axe

```

Lumberjack is just an empty GameObject. You then add an Animator to the Lumberjack and add Sprite Renderer components to both the Body and the Axe. Once you have done this create an Animator Controller and called it, say, Lumberjack Controller. Set this in the "Controller" field of the Animator (on the Lumberjack GameObject).

Within the Animator pane, now create a new Animation clip by clicking on the Create button in the image below.

For the purposes of this answer let's call it "Lumberjack Idle". You can now click on "Add Property" and add Sprite Renderer (or Transform, etc) properties independently for both the Body and the Axe children of the Lumberjack GameObject. This allows you compose two completely independent animations. You can get control over which appears on top by setting the "Order in Layer" value under the Sprite Renderer components of Body or Axe. The image below shows some options you have when you first click on Add Property. The idea would be to add Sprite Renderer/Transform/whatever properties for both the Body and Axe.

Here's an example for a tank I animated recently which was composed of a Tank Body, a Front, and a Top Turret.

As helpful as you might find this answer, I would highly recommend watching this video on the topic as it covers many more techniques than I have presented here.
> 0 votes

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


title: Design pattern for AI cooperation

text:
# Question
Title: Design pattern for AI cooperation
I'd like to implement an AI for my game, which has agents that should be able to take care of themselves.

The Sims use a system of smart objects that advertise their services, a design pattern that seems very nice since all the logic is hidden away in the object to be used, and it seems simple enough to get started.

I am currently stumped though how to extend it to interactions between multiple people, and to people using objects together, especially when it doesn't make much sense to use an object together. (I don't want a character to set up a boardgame and wait, no one comes and he leaves again)

# Answer
You can extend the smart object idea by including a voting system.

An unused chessboard periodically broadcasts "Anyone up for a game of chess?" while there are at least two agents nearby.

Agents in the vicinity evaluate whether chess would be good for their current needs/priorities and reply yes/no.

If the chessboard gets at least two "yes" votes, then it elects two players from among those who accepted. (This may be a good moment to use a matching algorithm if you have many agents nearby, to favour selecting a pair who already have a relationship)

One of the elected pair then vocalizes to the other "hey, how 'bout a game of chess?" and they proceed with the activity.

If the chessboard gets fewer than the needed number of "yes" votes in a round of voting, it goes back to waiting, with no visible activity revealing to the player the negotiation that just transpired.

An interaction between two agents can also use the smart object concept — but the agents themselves are the objects.

Each agent can periodically run through the set of actions it can perform with another and decide which are appropriate/desirable in this context. Then it can broadcast them as a smart object interaction available to agents nearby. "I'm down to chit-chat or high-five"

If another agent accepts the interaction, "I too would like a high-five" then the two begin the activity together, getting into position to play the corresponding animations.
> 1 votes

---
Tags: ai, simulations
---


title: Render output difference cause

text:
# Question
Title: Render output difference cause
There are two 3D applications compared side by side:

I'm looking for difference cause. These might be the cause, but I'm not sure:

* Color
* Lighting
* Shading code (GLSL)
* ?

Can anybody help me with detecting the difference cause?

# Answer
> 0 votes
Problem got resolved by changing Phong shading parameters of `ambient` color, `diffuse` color, `specular` color, `shininess` and `alpha`.

---

Previously these values were used:

```
// Colors components from 0 to 1 along with their corresponding hexagonal
ambient  RGB = (0.259, 0.522, 0.957) or #4285F4
diffuse  RGB = (0.49, 0.49, 0.49) or #7d7d7d
specular RGB = (1, 1, 1) or #ffffff
shininess    = 0.0

```

Result:

---

Replaced the above values with these:

```
// Color components from 0 to 1
ambient RGBA  = (0.015135135135135, 0.047675675675676, 0.07, 1.0)
diffuse RGBA  = (0.211891891891892, 0.66745945945946, 0.98, 0.5)
specular RGBA = (0.003027027027027, 0.009535135135135, 0.014, 1.0)
shininess     = 150.0

```

Result:

---
Tags: opengl, shaders, rendering, glsl, lighting
---


# Question
Title: Copyright information / issues (if any) for game
I have always been a fan of the game Heroes of Might and Magic 3 (let's call it simply HOMM3), which shined long ago, around 1998.

For more information, this game was created by the 3DO company - which sadly went bankrupt in 2003. Then in 2015, somehow it was 'revived' (a rendition, actually) as HOM3-HD edition by Ubisoft.

Now, I'm thinking of my own game that uses the theme from this game (well, at least use the game characters and audio for example), which might be published onto Google Play and/or App store.

So I'm wondering: would there be any issues (e.g. risks of being sued, for example by Ubisoft) if I try to use HOMM3 (the original one, as I called it above) art and audio ? For audio, I still own a copy of HOMM3 so I have access to the audio (MP3) files directly from the game folder. For arts, there are spritesheets like this: spriters-resource, which seem to be freely available to use.

These are two versions (owned by 3DO vs owned by Ubisoft), but things could get complicated if we are not prepared, so better be safe than sorry.

# Answer
> 2 votes
Using creative works from the game — including audio and visual assets, names of characters, etc. — without licence to do so is copyright infringement.

Just because the original company shut down does not mean legal rights to those assets lapsed or entered the public domain. Most often they just change hands to a new owner.

Buying a copy of the game does not constitute a licence to use its assets in derivative works. What you've bought is the right to play it, not distribution rights to its materials.

If you didn't make the asset, or pay the copyright-holder for a licence to use it, then it is not yours to use in your creations.

---
Tags: assets, copyright, licensing
---


# Question
Title: How do you handle aspect ratio differences with Unity 2D?
I've gotten a lot of answers to this question, but they are all generic and generally not very useful. None of the tutorials talk about aspect ratio and dealing with mobile devices and there are a zillion ways to do it, all seem to have gotcha's and flaws.

I really would love to know what successful games have used to handle different aspect ratios on iOS and Android without making a zillion different sized assets.

I am strictly speaking mobile, not desktop, specifically with Unity and I don't care about the UI, I only care about the gameplay canvas.

Issues I have in mind is when there are key things that have to be in certain places and cannot fall off the screen. Using black bars on top or bottom is unacceptable these days.

# Answer
> 46 votes
What you want is to constrain the camera viewport on portrait or landscape(depending on your needs), by computing `camera.orthographicSize` property, so you can build your 2d scene regardless of aspect ratio and resolution:

```
// Attach this script on your main ortohgraphic camera:

/* The MIT License (MIT)

Copyright (c) 2014, Marcel Căşvan

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */

using System;
using System.Collections;
using UnityEngine;

[ExecuteInEditMode]
[RequireComponent (typeof (Camera))]
public class ViewportHandler : MonoBehaviour
{
    #region FIELDS
    public Color wireColor = Color.white;
    public float UnitsSize = 1; // size of your scene in unity units
    public Constraint constraint = Constraint.Portrait;
    public static ViewportHandler Instance;
    public new Camera camera;

    private float _width;
    private float _height;
    //*** bottom screen
    private Vector3 _bl;
    private Vector3 _bc;
    private Vector3 _br;
    //*** middle screen
    private Vector3 _ml;
    private Vector3 _mc;
    private Vector3 _mr;
    //*** top screen
    private Vector3 _tl;
    private Vector3 _tc;
    private Vector3 _tr;
    #endregion

    #region PROPERTIES
    public float Width {
        get {
            return _width;
        }
    }
    public float Height {
        get {
            return _height;
        }
    }

    // helper points:
    public Vector3 BottomLeft {
        get {
            return _bl;
        }
    }
    public Vector3 BottomCenter {
        get {
            return _bc;
        }
    }
    public Vector3 BottomRight {
        get {
            return _br;
        }
    }
    public Vector3 MiddleLeft {
        get {
            return _ml;
        }
    }
    public Vector3 MiddleCenter {
        get {
            return _mc;
        }
    }
    public Vector3 MiddleRight {
        get {
            return _mr;
        }
    }
    public Vector3 TopLeft {
        get {
            return _tl;
        }
    }
    public Vector3 TopCenter {
        get {
            return _tc;
        }
    }
    public Vector3 TopRight {
        get {
            return _tr;
        }
    }
    #endregion

    #region METHODS
    private void Awake()
    {
        camera = GetComponent<Camera>();
        Instance = this;
        ComputeResolution();
    }

    private void ComputeResolution()
    {
        float leftX, rightX, topY, bottomY;

        if(constraint == Constraint.Landscape){
            camera.orthographicSize = 1f / camera.aspect * UnitsSize / 2f;
        }else{
            camera.orthographicSize = UnitsSize / 2f;
        }

        _height = 2f * camera.orthographicSize;
        _width = _height * camera.aspect;

        float cameraX, cameraY;
        cameraX = camera.transform.position.x;
        cameraY = camera.transform.position.y;

        leftX = cameraX - _width / 2;
        rightX = cameraX + _width / 2;
        topY = cameraY + _height / 2;
        bottomY = cameraY - _height / 2;

        //*** bottom
        _bl = new Vector3(leftX, bottomY, 0);
        _bc = new Vector3(cameraX, bottomY, 0);
        _br = new Vector3(rightX, bottomY, 0);
        //*** middle
        _ml = new Vector3(leftX, cameraY, 0);
        _mc = new Vector3(cameraX, cameraY, 0);
        _mr = new Vector3(rightX, cameraY, 0);
        //*** top
        _tl = new Vector3(leftX, topY, 0);
        _tc = new Vector3(cameraX, topY , 0);
        _tr = new Vector3(rightX, topY, 0);
    }

    private void Update()
    {
        #if UNITY_EDITOR
        ComputeResolution();
        #endif
    }

    void OnDrawGizmos() {
        Gizmos.color = wireColor;

        Matrix4x4 temp = Gizmos.matrix;
        Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
        if (camera.orthographic) {
            float spread = camera.farClipPlane - camera.nearClipPlane;
            float center = (camera.farClipPlane + camera.nearClipPlane)*0.5f;
            Gizmos.DrawWireCube(new Vector3(0,0,center), new Vector3(camera.orthographicSize*2*camera.aspect, camera.orthographicSize*2, spread));
        } else {
            Gizmos.DrawFrustum(Vector3.zero, camera.fieldOfView, camera.farClipPlane, camera.nearClipPlane, camera.aspect);
        }
        Gizmos.matrix = temp;
    }
    #endregion

    public enum Constraint { Landscape, Portrait }
}

```

If you need more info on this please ask and I will reply. ;) Regards and cheers.

**UPDATE:** Use Eliot Lash's object anchoring script together with this one to place objects at key positions on the screen if needed(relative to screen corners/borders).

Preview simulating various aspect ratios screens:

# Answer
> 6 votes
You typically don't need different sizes of assets - imported textures and sprites with automatically-generated mip maps will look nice when rendered at any size less than or equal to the original pixel size of the image.

The scene layout is the challenge. One good approach is as follows (and FYI I use a 3D camera looking at 2D content positioned at z=0):

1. Arbitrarily decide on a minimum "logical" display size in either pixels or tiles. This doesn't need to correspond to any real-world resolution, but it *should* reflect the narrowest/shortest aspect ratio that you want to support. For example, for a landscape game I wouldn't choose 480x320 because that's a wider aspect ratio than the iPad. So I might pick 1024x768 - or even 480x360, which gives me an original iPhone-sized coordinate system to work with and the same aspect ratio as every iPad (including iPad Air 2, etc.). Also note you can just as easily work in tile coordinates rather than pixel coordinates - 15x11.25 for example.
2. Program your game logic so that everything important is (or can be) positioned within your minimum display size but be prepared to fill extra room on the sides with additional content, even if it's just decorative filler.
3. Determine how much you need to scale your content so that either the width or the height matches the minimum value and the other axis is larger than or equal to the minimum needed. To do this "scale to fit", divide the screen pixel size by the minimum display size and take the smaller of the resulting scale values to be your overall view scale.
4. Use the view scale to calculate the effective (actual) display size for game logic purposes.
5. Actually scale your content by moving the camera along the Z axis.

In code form:

```
  // Adjust the camera to show world position 'centeredAt' - (0,0,0) or other - with
  // the display being at least 480 units wide and 360 units high.

  Vector3 minimumDisplaySize = new Vector3( 480, 360, 0 );

  float pixelsWide = camera.pixelWidth;
  float pixelsHigh = camera.pixelHeight;

  // Calculate the per-axis scaling factor necessary to fill the view with
  // the desired minimum size (in arbitrary units).
  float scaleX = pixelsWide / minimumDisplaySize.x;
  float scaleY = pixelsHigh / minimumDisplaySize.y;

  // Select the smaller of the two scale factors to use.
  // The corresponding axis will have the exact size specified and the other
  // will be *at least* the required size and probably larger.
  float scale = (scaleX < scaleY) ? scaleX : scaleY;

  Vector3 displaySize = new Vector3( pixelsWide/scale, pixelsHigh/scale, 0 );

  // Use some magic code to get the required distance 'z' from the camera to the content to display
  // at the correct size.
  float z = displaySize.y /
            (2 * Mathf.Tan((float)camera.fieldOfView / 2 * Mathf.Deg2Rad));

  // Set the camera back 'z' from the content.  This assumes that the camera
  // is already oriented towards the content.
  camera.transform.position = centeredAt + new Vector3(0,0,-z);

  // The display is showing the region between coordinates
  // "centeredAt - displaySize/2" and "centeredAt + displaySize/2".

  // After running this code with minimumDisplaySize 480x360, displaySize will
  // have the following values on different devices (and content will be full-screen
  // on all of them):
  //    iPad Air 2 - 480x360
  //    iPhone 1 - 540x360
  //    iPhone 5 - 639x360
  //    Nexus 6 - 640x360

  // As another example, after running this code with minimumDisplaySize 15x11
  // (tile dimensions for a tile-based game), displaySize will end up with the following
  // actual tile dimensions on different devices (every device will have a display
  // 11 tiles high and 15+ tiles wide):
  //    iPad Air 2 - 14.667x11
  //    iPhone 1 - 16.5x11
  //    iPhone 5 - 19.525x11
  //    Nexus 6 - 19.556x11

```

# Answer
> 2 votes
If you come around to using the bars it's actually pretty simple to implement (I'm posting this even though the OP stated the opinion of it being unacceptable because it has the benefit of being not near as bad on mobile and it's a simple solution that requires no code whatsoever)

`Camera.orthographicSize` is a variable within the ortho camera (which most 2D games use) that fits the measured amount of game units vertically on the screen (**divided by 2**) (source). Thus, pick an aspect ratio that fits the vast majority of devices (I chose 16:9 as most screens I researched are 16:9, 16:10, 3:2) and add a mask that overlays that at a ratio.

**Example**:

In my game (not listed here as this is not an ad, can ask in comments if desired) we use portrait mode. To do a nice simple 16:9 I made my Ortho camera at size 16. This means the camera will adapt 32 game units of height (y: 16 through -16 in my case) into the device's vertical of the screen.

I then placed black masks with a game between -9 and +9. Voila, the game's screen looks the exact same on all devices and a little skinnier on devices that are a little wider. I've had absolutely no negative feedback regarding the masks. To do landscape simply flip those values and then you'd make the camera of size 9. Change the values to match whatever you've decided is your game unit scale.

The only place we've observed the black bar to show up significantly is on the iPad at 3:2. Even then, I've had no complaints.

# Answer
> 1 votes
I'm doing this in a game I am currently working on. I have a background image that is 1140x720. The most important bits (the ones that should never get cropped) are contained in the 960x640 middle area. I run this code on the start function of my camera:

```
    float aspect = (float)Screen.width / (float)Screen.height;

    if (aspect < 1.5f)
        Camera.main.orthographicSize = 3.6f;
    else
        Camera.main.orthographicSize = 3.2f;

    float vertRatio = Screen.height / 320.0f;
    fontSize = (int)(12 * vertRatio);

```

I also define sizes other than font size for buttons and such. It works well on every aspect ratio I've tested. It's been a while since I set it up, so I may be missing a step. Let me know if it doesn't work as expected and I'll see if I left anything out.

# Answer
> 1 votes
@Marcel's answer and code are great and helped me understand what was happening. It's the definitive answer. Just thought someone might also find useful what I ended up doing for my specific case: since I wanted something really really simple, one sprite to be always on screen, I came up with these few lines:

```
public class CameraFit : MonoBehaviour {

    public SpriteRenderer spriteToFitTo;

    void Start () { // change to Update to test by resizing the Unity editor window
        var bounds = spriteToFitTo.bounds.extents;
        var height = bounds.x / camera.aspect;
        if (height < bounds.y)
            height = bounds.y;
        camera.orthographicSize = height;
    }
}

```

I added this to the camera and dragged my sprite (it's my background) to the script's only property. If you don't want any black bars (horizontal or vertical) you can put a bigger background behind this one...

# Answer
> 1 votes
This is an \>5 years old question, but it's still not only quite relevant, but also getting more and more complex over the years as there are even more screen ratios on mobile devices nowadays than even when this question was asked.

Since this question was ask, there have been quite a few additional options given in Unity (especially with Unity 2018). Still, there are quite a few tips & tricks when handling the screen ratio so that it can fit with *almost* every screen sizes.

**First, the best universal method is, ironically, the old method: Dynamically build whatever screen-related assets in real-time when, for example, a scene is started.** This is a similar thing to what is used for websites where you create a different kind of GUI & experience based on the screen sizes. For example, having a screen less wide than 800px would have 1 kind of GUI while having one of over 2000px would have another kind. It's really time consuming and relatively complex to build (hence more prone to bugs & errors), but offers the best versatility of any kind of setup. In such a way, your goal is to make sure every buttons and texts are always big enough to by pressed by people with big fingers and/or be read by anyone.

The main difference between doing it in a game engine (like Unity) and doing in HTML5 for the web is the fact that you're not stuck with a single "scene" in the game engine while HTML5 might requires you to work in a single web page as redirection scripts might be blocked by the User's browser. This means that you could start your game with a custom flash scene (such as a custom scene where your company logo appears) and, in that scene, you apply a checked that detect the screen sizes. Then, after, you make you scene transition script to decide which "scene" to load depending on the screen pixel sizes. This is far easier than having to script everything into a single scene.

The second way is a quite easier and faster, but it can have quite some impact on the performances depending on how good the optimization was applied. Simply put, **using a 3D space (known as "World Canvas" in Unity)** based GUI may saves you a ton of work. Unlike other kind of canvas, the World Canvas (3D based canvas) is getting automatically adjusted on the height of the screen based on its active screen rotation. This includes even a built-in Anti-Aliasing as well as a really good pixels ratio conversion of the textures using in the GUI which means that the GUI will look as if it was made especially for that screen resolution as long as each displayed textures doesn't exceed their maximum resolution. Another really important part of this method which is, for now, unique and can't be used with others is that this method also allow you to use basic VECTORS based graphics. Yup, for a while now Unity can render SVG files with flat colors. It's just not yet compatible with the GUI 5.x yet which is why this doesn't work with other GUI methods as this one is the only one who's using the proper Z-Buffer and some other built-in system of the engine to render the UI (which is why you can put both UI and 3D models in the canvas). Note that I precise that, for now, only basic Vectors based graphics can be used such as flat colors and really basic gradients (kinda like the limited HTML5 SVG-based code rendering). No outlines or styles or any kind of complex "rendered" magic can be done (yet?).

Lastly, the 3rd way is to use the "**Canvas Scaler**" component on the same GameObject as the Canvas' component. Usually, the best result comes from using the UI Scale Mode "Scale with Screen Size" and decide if the screen should be matching either the Width or Height of the target device. This methods comes with some restrictions and requires you to design something that can be well adjusted in one direction with a wide range of screen size. For this, I always suggest the use of something I call *fractal UI design*. This means to cut your menus in smaller sections while raising how "deep" the menus gets OR getting a menu design that allow you to display limited information at one time.

The best example I could give of how to cut a menu in smaller sections which widen the menu depth is making an option menu with tabs such as Sounds, Graphics, Gameplay, etc. Each of those tabs would have 1 to 5 options each at most. This can easily be displayed well on both small and big screens alike. You sacrifice maybe 60-80 pixel for the Tabs buttons, but you gain many times the remaining amount of pixels. As an example, the smallest yet still used Android-based screen size is 240x320 pixels. Yes, it's quite small, but it's surprisingly still used by some small devices in populated areas of China. If you avoid those, you avoid a tiny part of the market and the choice is yours. Personally, I usually focus on a basic of 480x800 pixels as a basic ratio & minimal screen sizes, but I keep looking at the GUI while in 240x320 now and then to make sure it's still "usable".

The quality of the 3rd method is that you can soft-launch the game with that method and, at a later point if necessary, apply an update that allow you to implement the 1st method. It's quite useful when you're on a tight budget and/or time allotment.

The downside of the 3rd method (and 1st) is mostly that you got to do quite a bit of maths when you're attempting to sync things properly. Such as having sprite-based animations with proper refresh rate based on the screen size because the sprite is tiled over the screen width or height is truly a pain to adjust properly without any wackiness.

As an example, one of my projects has a main menu with 2 animated gears that rotates and 2 chains that move up or down when the user change the menu selection. It's all in 2D and the chains are tiled at 100% pixel fidelity. This means that the chain seems "bigger" on a smaller screen slimmer on a bigger screen, but it has no weird pixels even if the screen reaches thousands of pixels in height. Yet the sprites of the chains are 53x254 and 33x254 and they are all part of a single Atlas 1024x1024 texture. To lighten the time requires to animate the UI properly, I created a general GUI animation script. Something that allows me to easily setup a list of GUI element so that they can animate by either rotation, changing sprites or by movement (translation) and this script's action can be remotely accessed by reference. Pretty straight-forward if you ask me. Still, to make it semi-universal, I had to add a few additional option (as Boolean parameters) that allows me to decide if the animation is affected by the screen ratio and on which direction if it's such a case. I noticed this to be needed when I tried the main menu on an old LG Android phone that has a, nowadays, unpopular screen ratio as the chain animation (which is based on the sprite switching speed like a sub-framerate) was 1.4x too slow while it was alright on more common screen ratios (like Android tablets) I tested it on.

P.S. If you wonder why I used **33**x254 and **53**x254 for the texture instead of numbers that are multiplication of 2, that is because of built-in Anti-Aliasing of the GUI textures where, sometimes, 1 additional pixel is read and displayed around resized GUI texture in a canvas. So while the texture size is 33x254, it sometimes display 34x254 pixels of the source. It's the usual float precision issue because of the resizing is done in floats (within the engine) that gets rounded up as integer for pixel reading.

# Answer
> 0 votes
There are a few ways to tackle this issue, and there isn't a perfect solution (at least I haven't found one yet) and the type of solution you go with is going to depend greatly on the type of game you're developing.

Regardless of you what you do, you should start off by picking the lowest possible resolution you'd like to support and build your sprites to that resolution. So if you're interested in developing for iOS, according to http://www.iosres.com/ the lowest iOS device resolution is 480x320.

From there, you can start scaling up the sprites to meet the higher resolutions. The caveat to this is that you'll eventually start to notice the sprites begin to blur the farther up you scale, in which case you can switch to another set of sprites built for the higher resolutions.

Or, you can ignore scaling completely, and just decide to display more of the game screen for higher resolutions (I believe this is how Terraria does it, for example). However, for many games, this isn't appropriate; competitive games for example.

> Using black bars on top or bottom is unacceptable these days.

Is it? Lots of games that want to force 4:3 aspect ratios do this. Since you're using Unity, you can make use of the AspectRatioEnforcer script to aid in this.

# Answer
> 0 votes
There are multiple ways to handle this issue, it depends on your game and what will work best. For example, on our game Tyrant Unleashed we simply made wide maps with unimportant detailing on the sides, so that it's okay to cut off the sides on narrower devices. However other games might be better with an approach where you actually shift buttons around or something to fit the screen better.

(also part of our approach is also keeping a consistent height on all devices, only varying the width. This certainly makes life easier for us, but again this may or may not be any good for your specific game. It doesn't matter in our art style if the images are scaled a bit on different screens, whereas this might matter for something like pixel art. Basically, this is the "let Unity handle it" approach)

# Answer
> 0 votes
I'm using the following script which adds a `targetAspect` parameter to the camera and adapts its `orthographicSize` with respect to the screen ratio (more details in this blog post):

```
using UnityEngine;
using System.Collections;

public class AspectRatioScript : MonoBehaviour {

    public float targetAspect;

    void Start ()
    {
        float windowAspect = (float)Screen.width / (float)Screen.height;
        float scaleHeight = windowAspect / targetAspect;
        Camera camera = GetComponent<Camera>();

        if (scaleHeight < 1.0f)
        {
            camera.orthographicSize = camera.orthographicSize / scaleHeight;
        }
    }
}

```

# Answer
> 0 votes
The best solution for me is to use the theorem of intersecting lines so that there is neither a cut off on the sides nor a distortion of the game view. That means that you have to step back or forward depending on the different aspect ratio.

# Answer
> 0 votes
My method is mostly similar to the solutions given by others :) I'll try to explain in detail the approach which I take to make the game independent of the screen size.

**Screen Orientation**

Depending upon the screen orientation (Landscape or Portrait) , you need to consider whether the camera will scale with a fixed height or fixed width. Mostly I choose fixed width for landscape oriented games and fixed height for portrait oriented games.

**Camera Scaling**

As discussed this can be either fixed height or fixed width.

*Fixed Height*: The vertical area of the game will always fit to the screen height. And as the screen aspect ratio changes there will be extra space added to the left and right of the screen. To implement this you don't need to code anything, it is the default behaviour of unity camera.

*Fixed Width*: The horizontal area of the game will always fit the screen width. And extra space will be added to the top and bottom as the aspect ratio of the screen changes. To implement this you need to write a small piece of code. Later on make sure you remove the code form update function, and place it in awake.

```
using UnityEngine;

[ExecuteInEditMode]
public class ScaleWidthCamera : MonoBehaviour {

    public int targetWidth = 640;
    public float pixelsToUnits = 100;

    void Update() {

        int height = Mathf.RoundToInt(targetWidth / (float)Screen.width * Screen.height);

        camera.orthographicSize = height / pixelsToUnits / 2;
    }
}

```

In the editor you can change the targetWidth to define the world space area you want to display. This code is explained in the following video along with many other practices for 2D games :)

Unite 2014 - 2D Best Practices In Unity

**Aspect Ratio**

Following aspect ratio listed from widest to narrowest, covers almost all the screen sizes for both android and iOS

* 5:4
* 4:3
* 3:2
* 16:10
* 16:9

I usually set all of these aspect ratios in the given order under the game window, as it is handy while testing for different screen sizes :)

**Expendable Area**

This is the area which gets added to the screen to the sides or top/bottom depending upon the camera scaling you have chosen.

For fixed height all the game elements should preferably fit in 16:9 ratio which is the narrowest. And the background should extend till it covers the 5:4 ratio. Which makes sure that your game never has black strips to the sides.

For fixed width it almost the same but here the elements should fit in 5:4 ratio and the BG should extend till 16:9.

**Bounds**

Sometimes we cannot use the expendable area approach as we need to utilise the whole available screen for the game play.

For example , consider a portrait game with fixed height , catching the coins falling from the sky. In this we need to give the player ability to move horizontally over the available screen width.

Hence we need the bounds of the camera in terms of world co-ordinates to know where exactly the left,right,top or bottom of the camera clips at the world position.
We can also use these bounds to anchor game elements or UI to a desired side of the camera.

Using Camera.ViewportToWorldPoint we can get the bounds.Viewport space is normalized and relative to the camera. The bottom-left of the camera is (0,0); the top-right is (1,1). The z position is in world units from the camera. For 2D/orthographic the z doesn't matter.

```
Vector3 leftBottom = camera.ViewportToWorldPoint(new Vector3(0, 0, camera.nearClipPlane));
Vector3 rightTop = camera.ViewportToWorldPoint(new Vector3(1, 1, camera.nearClipPlane));

float left = leftBottom.x;
float bottom = leftBottom.y;
float right = rightTop.x;
float top = rightTop.y;

```

**UI**

For UI we can apply the same concepts that we used for the game elements. After introduction of Unity5 UI and availability of plugins like NGUI this won't be much of a problem :)

# Answer
> 0 votes
I created the Unity Asset 'Resolution Magic 2D' to solve this very problem (ad: you can get it from the Unity Asset Store, or see more details at grogansoft.com).

The way I tackled the problem was as follows...

Define an area of the screen that must always be visible regardless of aspect ratio/resolution, and use a simple rectangle transform to 'stencil out' this region. This is your ideal screen shape. Using a simple algorithm I then zoom the camera until the region blocked out by the rectangle is as large as possible while still being 100% visible to the camera.

Then your main game area is always taking up as much screen as possible. And as long as there is sufficient 'extra' content (e.g. your background) outside of the rectangle area you defined before, players whose screen is not the same aspect ratio as your 'ideal' rectangle will see the extra content where black bars would otherwise go.

My asset also includes some logic for placing UI, but that is mostly obsolete due to Unity's new UI system.

My asset provides this out of the box with minimal setup, and it works really well on all platforms.

If you use this technique (or my asset), just make sure you design your game to have 'optional' space all around to accommodate screens that are wider or taller than your ideal (to avoid black bars).

I don't personally make 3D games, so I don't know if this would work in 3D (or if it is even necessary).

It's really hard to explain without pictures, so please visit my website (Resolution Magic 2D)

# Answer
> -3 votes
I created a AssetStore extension that allows for easier aspect switching called AspectSwitcher. It provides a system for allowing you to easily specify different properties for different aspects. There are generally two method that most people use to switch aspects. One is to provide different game objects for each aspect. The other is to create custom code that modifies the properties of a single game object based on the current aspect. That generally requires a lot of custom coding. My extension attempts to alleviate a lot of that pain.

---
Tags: unity, mobile, aspect-ratio
---


# Question
Title: How to find a valid point if NavMeshObstacle is blocking path?
Is there any way to find the closest valid point to my target if a NavMeshObstacle is blocking my agent's path? This point can be any point along the red line in the image above.

# Answer
> 2 votes
NavMesh.CalculatePath does return you a partial path if it cannot reach the destination. You can try reading the last corner of the path that you get returned.

Source: https://docs.unity3d.com/ScriptReference/AI.NavMesh.CalculatePath.html

---
Tags: unity, navmesh
---


title: How do we convey scale in 2D games?

text:
# Question
Title: How do we convey scale in 2D games?
What methods can one use to let the player experience the size of a game world in a 2D game, be it Isometric or Orthogonal?

When playing an open-world game in 3D, the player often is able to rotate the camera to see a building or mountain they can walk to. This creates (at least for me) a feeling of scale, the desire to go there and a feeling of accomplishment, as soon as the desired location is reached.

Is there a technique or game-mechanic that can let players have a comparable perception of scale in a 2D game?

# Answer
Large, open areas do not work very well in top-down 2d. Putting the player in such an area just disorients them. It is much better to use more complex areas which limit the way the player can navigate.

So you need some other way to communicate the scale of the world to the player. A common way to do that is by providing them with a world map they can access at any time and which shows them their current location in the world as well as all the locations in the world they can explore:

*Zelda: A Link to the Past*, ©1991 by Nintendo

That map might even be navigable itself. A common JRPG trope is to have lots of small-scale local area maps connected by an overworld map in a much larger scale. This allows you to place locations in your game world at plausible distances without having to create lots of high-detail low-relevance maps in between them the player needs to explore up close:  *Final Fantasy 4*, ©1991 by Square

You might even use a different camera perspective for traveling *between* locations than you use for traveling *within* locations. Even if 99% of your game takes place in an isometric or orthogonal 2d perspective, your travel mechanic might still use a 3d or pseudo-3d perspective which does a better job at conveying the scale of your world:

*Secret of Mana*, ©1993 by Square
> 50 votes

# Answer
I believe the answer lies in 2.5D

If your game is a 2D sidescroller, then you may rely on parallax scrolling, shadows and lighting to convey size and scale better.

If your game is a 2D topdown or isometic, your scale will benefit from assets that get drawn above the player (such as trees that extend above their own tile). Once again, shadows and lighting are what convey actual scale perception.

Artificial camera work might also be worth looking into for cinematic sequences that you can use to force the player to look at certain things.
> 19 votes

# Answer
Conveying scale accurately can be tricky in 2D games. There are other ways of conveying that "go this way to reach this objective" feeling, but you have to think about it within the medium itself, instead of trying to translate 3D methods into a 2D world.

A 2D view gives you a better awareness of all nearby objects than a 3D one - you don't *need* a mountain in the distance for the player to orient themselves when they spin the camera around, because they can see around themselves at all times. Instead, you'll want to scatter smaller environmental clues around them to let them know that they are going the right way.

Many open-world adventure games divide the world into "crossroads" and "paths". At the crossroads, place a clue that can help the player identify what they will find in each direction. For example, let's say there's a crossroads, and one path leads to the town, one leads to a lake, and one leads to a forest. Put a tree or two near the forest path, have a river leading toward the lake, and a paved road leading into town, and make sure they are all visible from the same screen. Each "path" can be more variable, but once the player has chosen a path they will usually keep walking that way unless there are obvious clues that they are going the wrong way.

One tried-and-true method that works in both 2D and 3D is to scatter "breadcrumb trails" leading toward interesting locations. This can include small pickups like coins, but there are other, more subtle methods - anything that the player will want to check out can help guide them, without feeling as restrictive as a walled-off path. One tactic I like using to help players find their way through towns (which usually allow the player to wander in any direction) is to always have at least one new NPC (or other obvious "object of interest") visible from every other NPC location. Even if the player *can* walk anywhere, until they get the "lay of the land" they will tend to follow the "trail" of NPCs in an attempt to check everything out. (This also lets you reveal information to them "in order" without being explicit about it - the player *feels* like they are wandering freely and talking to people at random, but they really aren't).

Landmarks are key. It's better to have a smaller world where every single screen has an interesting object or formation than a sprawling world where everything looks the same. This is true in all adventure games, but doubly so in 2D where the only clues the player has to their location are nearby objects.

If the destination is towards an enemy stronghold, you can place stronger enemies as they get closer. This not only helps the player find their way, it also keeps weaker players from traveling too far until they become stronger, without explicitly locking them out of high-level areas, and creates a feeling of progress and accomplishment when they have grown strong enough to survive in the more dangerous regions.

Finally, if you want to create the same feeling of "awe" you get when walking toward a vast mountain/castle/etc in a 3D game, create "lookout points" such as cliffs or the top of towers where the destination is in the background, using parallax and lighting effects to create a sense of distance - this is where you focus on those artsy single images. The use of this will restrict the orientation of your world somewhat - for top-down Zelda-esque games, you can pretty much only have lookouts showing objects to the north - but generally in games like these, mountains and castles are approached from the south anyway.
> 10 votes

# Answer
In addition to all the great answers, here's another part in the mix that can expand the perceived scale -- **content clues**:

* A horse cart is racing by, apparently towards some grand destination
* A signpost points to "Castle 5 miles this way"
* A "Traveler's Inn" by the road has people resting from the "long road from and to Landmark"
* A flock of birds travel by, apparently they have a destination far away
* The townspeople in dialogue warn you of dangers afar, or mention treasures ahead
* A group of citizens hurriedly walk past you
* Your own character when idling holds up a binocular to look at something out of sight
* Objects and particles from further away places get blown into view by the breeze, like desert shrubs
* A burned house shows charcoal footprints leading away
* The travel guide at the town hall talks of glorious distant places
* Sounds like far-away shrieks introduce distant themes
* Moving clouds and a storm slowly brewing up, from little rain drops to a big shower, convey an overarching large system of moving weather phenomena
* Ponds mirror the clouds, and -- with some creative freedom as to how reflection works -- maybe they even mirror a far-away castle
* Windows in houses, similar, reflect far away landmarks
* Your character could pose and gesture in awe when they are idling and see something exciting outside the screen

... and on top, maybe the game is literally called The Vast Lands, Infini-World, Endless Roads, Gigantic Continent, or any variation thereof, priming the player for huge scale!
> 7 votes

# Answer
One way of conveying distance in any game is to make it take a long time to get from one place to the other.

One of the largest game worlds in my memory is a MUD I used to play that artificially separated provinces by sea voyages that took anywhere from a few minutes to a few hours. Within each province, it was fairly quick to walk from one place to another, so when one thought about going to another province-- particularly one with a couple other provinces in between-- there was a sense that it was very far away. There was one province in particular that took a very long time to travel to, and whenever one went there, it felt very *remote*. The areas there were not well-documented and always devoid of people, and so they felt very awesome and mysterious when you finally came upon them.

Some find artificial time delays to be an obnoxious game mechanic, but that is one way you can add a sense of scale to the world, independent of graphics.
> 3 votes

# Answer
Fast travel is often used to convey scale, in both 2D and 3D games. As this answer mentions, time is an effective substitute for scale, but with a graphical game you do not want artificial delays, so make the delays the real effect of having a large world.

Most games will have a smaller "intro" area, and if this area is large enough it can take some time to walk from one side to the other. This will make the intro section seem like it's large enough to hold a whole game. Inside this area NPCs or other exposition can mention places far away that seem unreachable, until the intro section opens and allows the player into the larger world, and the player quickly realises it would take unreasonably long to just walk everywhere - but outside there are faster forms of movement.

You can repeat this as often as you can come up with novel barriers and forms of movement to overcome them - perhaps you need horses to move effectively outside the intro section, but then you find yourself stuck on the continent, which doesn't seem so bad because the continent is large - but then you discover you can board a ship, which lets you visit places further away, etc.

A good example of this is Zelda Breath of the Wild, where everything you can see you can travel to, but it doesn't seem that way at first while you're stuck on the plateau - you don't realise the full scope until you start the long walk towards something in the distance. You can achieve the same thing in 2D, by making travel times long (requiring other forms of transport) and by having in-game exposition (NPCs, books, map fragments, legends) mention far-off places as if they're far-off and unreachable - until you do find a way to get there.
> 2 votes

# Answer
If what you want is the a similar *feeling* to a open world 3D game, you can make 2d assets of your mountains, castles and such and have a "look around" mode where you arrange all that in a set of parallax layers. I don't remember seeing that in any game so maybe it has some obvious flaw I'm not considering. You'll also want to use fog of war in your world map, otherwise the look around feature won't have any gameplay-related usage.
> 1 votes

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


# Question
Title: Box2d Raycast C++. Always returning false? (trying to check if player is grounded)
I'm trying to add Box2d to my C++/SFML platformer game. I have my ground tiles with a b2staticBody. And the player character is b2\_dynamicBody.

My usual method to check if player is grounded is to Raycast straight down from centre of sprite to just below the foot level. (NOTE: I do note that SFML is y-down).

For now, I just want the raycast to return true if it hits anything. But it always returns false. I watch the player land on the ground and can walk along the floor and fall off it (ie. The built-in box2d collision is working)

Here is my code (I am brand new to using Box2d in c++, so sorry if it's wrong. There aren't too many good examples to be found online)

```
void guy::update() {
bool bGrounded = false;
b2RayCastOutput output;
b2RayCastInput input;
input.p1 = bodyPtr->GetPosition();
input.p2 = bodyPtr->GetPosition() + b2Vec2(0, 1.f * Constants::PPU);
input.maxFraction = 1.0f;
b2Fixture* fixture = bodyPtr->GetFixtureList();
std::cout << "p1: " << input.p1.x << " , " << input.p1.y << " / p2: " << input.p2.x << " , " << input.p2.y << std::endl;
std::cout << "sprite pos: " << sprite.getPosition().x << " , " << sprite.getPosition().y << std::endl;
if (fixture->RayCast(&output, input, 0))
{
    bGrounded = true;
}
else
{
    bGrounded = false;
}
std::cout << "isGrounded: " << bGrounded << std::endl;
}

```

The console outputs seem ok (ie. p1 and p2 are where I expected them to be), but the bool always returns 0.

Of course I am very open to an improved jumping function. Eventually I want to be able to add the ability to hold the jump button for some time to get a bigger jump. But the only way I can think to start with is checking if the player is touching ground first.

NOTE: Here is the ground Tiles start function (at the bottom you see i CreateFixture():

```
void Tile::start(size_t x, size_t y, sf::Texture& texture, bool isSolid, b2World* world)
{
worldPtr = world;
bIsSolid = isSolid;
sprite.setTexture(texture, true);
sprite.setOrigin(sprite.getTextureRect().width / 2.f, sprite.getTextureRect().height / 2.f);
sprite.setPosition((float)x * Constants::PPU, (float)y * Constants::PPU);

if (isSolid)
{
    bodyDef.position.Set(sprite.getPosition().x, sprite.getPosition().y
    );
    bodyPtr = worldPtr->CreateBody(&bodyDef);
    b2Vec2 topEdge(-1, 0);

    box.SetAsBox(sprite.getTextureRect().width / 2.f, sprite.getTextureRect().height / 2.f);

    bodyPtr->CreateFixture(&box, 0.f);

}

}

```

Here is the player start() in case it will help:

```
void Guy::start(b2World* world)
{
worldPtr = world;
texture.loadFromFile("Textures/guy.png");
sprite.setTexture(texture, true);
sprite.setOrigin(sprite.getTextureRect().width / 2.f, sprite.getTextureRect().height / 2.f);
setPosition(4 * Constants::PPU, 10 * Constants::PPU);

bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(sprite.getPosition().x, sprite.getPosition().y); // TODO: Does this need to be offset?
bodyPtr = worldPtr->CreateBody(&bodyDef);

box.SetAsBox(sprite.getTextureRect().width / 2.f, sprite.getTextureRect().height / 2.f);

fixtureDef.shape = &box;
fixtureDef.density = 65.0f; // TODO Magic numbers
fixtureDef.friction = 0.05f;

bodyPtr->CreateFixture(&fixtureDef);
bodyPtr->SetFixedRotation(true);

}

```

# Answer
OK well eventually I think i found the answer (I was WAY off when I originally wrote the question).

As I think Vaillancourt was alluding to in the comments above, I wrongly thought the only way to RayCast in box2d was via the b2Fixture class. There is in fact a RayCast function on b2World also.

Trying this World RayCast instead brought out a new problem for me. I couldnt understand what it wanted in the 'b2RayCastCallback' parameter of the method. From learning how to fix this, I think i learnt a lot about box2d and c++ in general so I am really happy to got this far by myself. (NOTE: If anyone experienced reads this and see's I am still wrong , please feel free to correct me, or edit the answer.).

I had to create a new class , **which inherits from b2RayCastCallback** **(public)**. It only had one function i had to implement called ReportFixture. Then I created member variables to use as 'out' variables. I also created a constructor that sets a bool 'bHit' to false upon construction, the bHit bool is set true as soon as Ray hits something (which in turn leads it to call ReportFixture method that I implemented from base class.

Here is the new code which does now report in the console when my player character lands on the floor objects.

inside my player update:

```
void Guy::update(float deltaSeconds)
{
MoveSideways();

bool bGrounded = false;
RayCastCallback callback;
b2Vec2 p1 = bodyPtr->GetPosition();
b2Vec2 p2 = bodyPtr->GetPosition() + b2Vec2(0, 0.51f * sprite.getTextureRect().height);
worldPtr->RayCast(&callback, p1, p2);
if (callback.bHit)
{
    // We have a hit, it must be the ground (I hope.. :S) ...
    std::cout << "bHit" << std::endl;
}

```

New 'RayCastCallback class' I made:

```
 /// .h file
#include "box2d/box2d.h"

class RayCastCallback : public b2RayCastCallback
{
public:
RayCastCallback();
// Inherited via b2RayCastCallback
virtual float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction);

bool bHit;
b2Fixture* out_fixture = nullptr;
b2Vec2 out_point;
b2Vec2 out_normal;
float out_fraction;

};

/// .cpp file:

#include "RaycastCallBack.h"

RayCastCallback::RayCastCallback()
{
bHit = false;
}

float RayCastCallback::ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction)
{
bHit = true;
out_fixture = fixture;
out_point = point;
out_normal = normal;
out_fraction = fraction;
return 0; // there a different options for return here that allow the ray to continue or stop etc (see notes in base class)
}

```
> 0 votes

---
Tags: c++, box2d, sfml
---


title: Different resolution for UI?

text:
# Question
Title: Different resolution for UI?
I'm developing my first game for mobile devices in Unity3D. My game uses a 720p-resolution. Currently the UI uses the same one. So far so good.

I heard that professional game-developers create their games in a way where the UI uses a much higher resolution than the game itself in order to deliver high-definition graphics for the UI-system.

So in my case does that mean I have to create a much higher resolution for the UI so it looks crisp and sharp even on large mobile-displays (e.g. tablets like the iPad Pro, etc.)? Is 1080p a good resolution for the UI I'm creating? Or shall I stick with 720p? If I use e.g. 1080p for the UI do I need to scale down the UI in Unity3D?

# Answer
tl;dr - Unity user interfaces use a Canvas Scaler to help deal with these issues. You can use high resolution assets and Unity will scale them appropriately, including drawing higher resolution things on those screens.

Interestingly, "pixel perfect" is actually more work.

A lot of the complexity comes from deciding what resolutions and kind of scaling you want to support. For example, if you are just targeting televisions, you might have a 1920x1080 (aka 1080p) target. If the title runs on a 4k TV, the resolution might increase but the layout won't. For this you might use the Canvas Scaler in Scale With Screen Size mode.

Compare that to a typical iOS app, where the user expects the DPI to stay the same (i.e. 144ppi or whatever) but the screen space changes. In that model you might want to use Constant Physical Size.

You can import high resolution sprites and let Unity scale them. That's on the UI/sprite import settings.
> 1 votes

---
Tags: unity, gui, image, resolution
---


# Question
Title: Is a Stamina Bar (ala Dark Souls) a good idea for a casual player target group?
We all know the "Stamina Bar". For those who dont: Its a "Bar" (usually right below your life-bar) which prevents spamming the attacks as much as you want. Attacking will also reduce your stamina and you need a certain amount of stamina to use Attacks. Usually blocking , rolling and other things also require and reduce your stamina. Its a great way to balance the a real time action battle system. You can upgrade your stamina which is cool too because gives you a feeling of progress and add a little bit of fun there.

Anyway:

The Question here is:

Is this "okay" for "Casuals"?

I have a game which is open-world-ish and you can walk around and fight enemies and fight bosses too. But the game seems "too easy" now. You can basically just spam your attack button and every enemy is easy. Even the bosses.

A way the fix this is the stamina bar.

But wouldnt that overwhelm the casual players ?

# Answer
> 2 votes
Just like so many things in game design: it depends on the implementation.

* Are the mechanics surrounding your stamina bar simple enough to understand?
* Are you able to communicate these mechanics properly during your tutorial?
* Considering all the other mechanics you alreadey have in your game, is there space in your player's minds for another one?

If you answer "yes" or at least "maybe" to these questions, then it is worth trying. But in the end there is just one way to find out if it makes your game better or worse: playtesting with fresh people from your target demographic.

Also note that the concept of a stamina bar won't be foreign to most casual players. A lot of free-to-play mobile and web games use stamina bars. Usually though they take hours to refill, not seconds. Their purpose is to artificially slow down the player's progress and then tease them to remove that limitation through microtransactions. But you could still try to build on that familiarity to communicate the purpose of your stamina bar.

# Answer
> 1 votes
I haven't played Dark Souls, so i don't know how this stamina bar feels to play, but i would say it depends on how your combat system is designed. In my opinion using the same resource for everything does not sound like a good idea. The Problem with this is, that you can't do anything, when the resource is gone.

My idea to this Problem would be make at least two different resources. One for blocking, sprinting, rolling and other movement. The other one for attacking (like Mana in many games) and an attack skill you can always use. So it doesn't matter what happens, you can always walk and attack with a weak move. But you have to watch the resources for better movement and attacking. Ok, maybe one resource for both would work, but you shouldn't take away every possible action from the player. Thats why i would let him always a weak attack.

One or two bars shouldn't be a problem for casuals, if you explain what they do. But then the balancing gets very important. If the bars are too small it will be frustrating, if they are too bit, they won't matter.

If your only action is hit the Enemy with the sword maybe you should work at this before making a stamina bar. Running away from an enemy with 10% life because you can't attack him and you have to wait for stamina doesn't sound like fun.

For the Bosses. I always liked interesting mechanics more than resources. If they are too easy, give them a few devasting attacks with a big indicator, so it's possible to dodge them. Maybe make them only vulnerable after such an attack because if they fail, they stun themselves or something like this.

Easy games can also be fun. And remember: you designed the fighting system. Maybe attacking and blocking isn't that easy for other players. Let a few friends try your battle system and ask them what they think about it. Probably they can give you better feedback than everyone here who is just reading your question.

# Answer
> 1 votes
> I have a game which is open-world-ish and you can walk around and fight enemies and fight bosses too. But the game seems "too easy" now. You can basically just spam your attack button and every enemy is easy. Even the bosses.

... And your solution is stamina. What are the alternatives?

A classic solution for this is to put a cooldown on attacks.

However, let us go back even further... You can have the character committed to an animation. Dark souls does this too. That could be enough for your situation.

Other solutions include attacks push enemies out of the way, so that spamming attack does not hit them. Also using an invulnerability period (a fraction of a second) to enemies after each attack, so that you will get hit if you try to spam.

*Alright, so, this random person comes running at you and start poking you with a stick. What do you do? Block? Disarm? Run away? Hit back? Get staggered and wait until you die? You can make enemies harder by having then react smarter.*

These all serve different goals in your design. You must think what kind of play do you want to encourage. Should, for example, the player be calculating every attack? Or should the player be taking more ground after each attack?

*You also need to be careful to communicate whatever mechanic you pick.*

---

The problem with stamina is the down time. You do a burst of attacks, and then you have to step back to recover it. Meanwhile, what is there to do? Not much really. It is down time. Not engaging. Boring... *Oh, an enemy is attacking! Avoiding it takes stamina too? Darn you stamina!*

Taking this to casual players, for some definition of casual, will probably go wrong. If your target audience is people who plays in small chunks of time, then value their time!

*The same goes by giving invulnerability phases to enemies, and designing combat based on waiting for the enemy to lower its guard. Value the player's time.*

If you are going to use stamina, you need to give the player something to do when they have no stamina. Better yet, give the player something to do about it.

# Answer
> 0 votes
That will depend on how you implement it.
If you aim for a casual player base you may not want to make the stamina managing too relevant, at least not all the time so the easier way is:
**The sum of the damage dealt plus the needed rolls blocks etc that the player need to do, in order to defeat a common enemy should have a stamina cost lesser than a full stamina bar.** This way players should only worry of stamina when facing multiple enemies or bosses.
This is of course a starting point and a lot of balance and player test is needed but it should put you in the right path.

# Answer
> -2 votes
As a casual gamer I despise the stamina and it seems like all the new action games have implemented this from Nioh to the Surge to Code Vein and it just stifles gameplay and this trend needs to stop! I am sick and tired of these Soulsborne clones! They've ruined the genre and I hope this fad dies off sooner than later. I'm currently working on a classic DMC/Bayonetta/Darksiders game and I WILL NOT include a stamina bar.

---
Tags: game-design, combat
---


# Question
Title: Unity Facebook WebGL build... Does this work or not?!?! Getting conflicting answers
So here is the facebook documentation..

It seems to be saying you can output a Facebook WebGL build from Unity and upload it. It does not work for me, I get this message when I upload.

"Games must reference one of our supported SDKs via our CDN."

Theres also this thread, with people saying it is not supported.

https://forum.unity.com/threads/facebook-instant-games-support-html5.499198/

Yet the latest version of Unity has a WebGL option when building to Facebook platform.

What is going on? Does or doesn't this work?

# Answer
In case anyone comes across this and was confused like I am-

Facebook no longer separates Web Hosting from Instant Games; to upload a build, upload it under Instant Games/Web Hosting, then disable "Use Instant Games" in the Instant Games settings to have a facebook web game, not instant game.

If you run across the "Games must reference one of our supported SDKs via our CDN." error, I found a weird solution - make a test app, then upload the build under that test app. Go back to the main app and your build will be there.
> 3 votes

# Answer
You have to add a reference to the sdk in index.html file.

src="https://connect.facebook.net/en\_US/fbinstant.6.3.js

Adding the above line into you index.html file will solve the issue.(Add the script tag ).
> 0 votes

# Answer
BLeh forget it... Facebooks site is just a mess. I was getting 'Instant games' and 'webhosting' mixed up
> -2 votes

---
Tags: unity, facebook, build-process, unity-webgl
---


# Question
Title: How to make switch work with enum? C# Unity
I'm working on a script to fade UI elements in Unity, similar to a selector, where you can select the type of fading, and duration, and image to fade

I found that enum is the best option to achieve that result, but I have a problem, when I run the code only element of the enum work and the other don't, no matter if I use switchor if just the first statement run, I don't know what's wrong with the code

* Please explain your answer
* Please explain why the code is wrong
* Please give feedback on how to improve

I'm using Unity version 5.3.5f1 and Visual Studio Community 2015

**Goal**

* Make the enum work properly using either switch or if
* Be able to use the variables inside the FadeOperations class to make the calculations inside the Test class
* Select from an array the type of desired operation
* Select an UI element from Heriarchy and fade it

**Steps**

* Create new Unity project (2D or 3D)
* Create UI Image
* Create Empty game object
* Create new C# script (I called it Test)
* Attach new script to empty game object

**Code**

Here's my code so far...

```
using UnityEngine;
using UnityEngine.UI;

 public enum FadeManager
 {
     fadeIn,
     fadeOut
 };

 [System.Serializable]
 public class FadeOperations
 {
     [Tooltip("Type of fading")]
     public FadeManager fadeType;

     [Tooltip("Duration time of the fading")]
     public float duration;

     [Tooltip("Select the image to fade")]
     public Image fadeImage;
 }

 public class Test : MonoBehaviour
 {
     [Tooltip("Select your type of fade")]
     public FadeOperations[] fadeOperations;

     //Reference to the class FadeOperations
     private FadeOperations _fo = new FadeOperations();

     //Loop for debug
     private void Update()
     {
         switch (_fo.fadeType)
         {
             Debug.Log(_fo.fadeType)
             //This statement works
             case FadeManager.fadeIn:
                 Debug.Log("Fadein"); //Only this piece of code works
                 break;

             //This statement doesn't work
             case FadeManager.fadeOut:
                 Debug.Log("Fadeout");
                 break;
         }
      }
  }

```

The result of the Log (\_fo.fadeType) before the switch

```
fadeIn
UnityEngine.Debug:Log(Object)
Test:Start() (at Assets/_Scripts/Test.cs:34)

```

# Answer
Your switch statement is checking `_fo.fadeType`. Because `_fo` is private without `[SerializeField]`, it won't show up in Unity's Inspector tab unless you enable Debug mode.

Your code has `_fo = new FadeOperations();` which creates a new `FadeOperations`, and the `fadeType` is `FadeManager.fadeIn` by default since it's first in the enum, and that's what's being cased every time.

If you write it as:

```
[SerializeField] private FadeOperations _fo = new FadeOperations();

```

^ this will show the `_fo` variable in the Inspector, and you can see the value, as this is what your switch statement is checking against.

Based on your `public FadeOperations[] fadeOperations;` line, I assume you've added at least one FadeOperation via the Inspector to this array. Perhaps you'd instead want to make your switch statement check the first item in the array:

```
switch (fadeOperations[0].fadeType) {

```
> 2 votes

# Answer
This is an example of an `enum` being used in a `switch` statement. I hope that this helps you.

```
using UnityEngine;
using System.Collections;

public class MyScriptFile : MonoBehaviour
{
    // Define possible states for enemy using an enum
    public enum EnemyState {CHASE, FLEE, FIGHT, HIDE};

    // The current state of enemy
    public EnemyState ActiveState = EnemyState.CHASE;

    // Update is called once per frame
    void Update ()
    {
        // Check the ActiveState variable
        switch(ActiveState)
        {
            // Check one case
            case EnemyState.FIGHT:
                {
                    //Perform fight code here
                    Debug.Log ("Entered fight state");
                }
                break;

            // Check multiple cases at once
            case EnemyState.FLEE:
            case EnemyState.HIDE:
            {
                //Flee and hide performs the same behaviour
                Debug.Log ("Entered flee or hide state");
            }
            break;

            // Default case when all other states fail
            default:
            {
                //This is used for the chase state
                Debug.Log ("Entered chase state");
            }
            break;
        }
    }
}

```
> 1 votes

# Answer
As already discussed, your use of enums in a switch statement is actually correct. Your problem is that your checking against a private variable that you only initialise, rather than the public variables that *might* offer differant values. As a result, the switch statement will *always* trigger the `case:FadeManager.fadeIn` case, because a `FadeManager` variable that has been *initialised*, and *only* initialised, will only ever report the default value.

## Enums in Switch Statements

As mentioned, your code is correct. Using enums as follows will work correctly, providing you check the correct variable. For the purpose of extending your understanding, I will also mention the `int` option; while it will likely always be redundant to do so, you could also check against integer values. The integer would need to correspond with a valid index number in your enum, and would still need to be cast as a type of your enum.

```
public enum FadeManager
{
    fadeIn, // index 0
    fadeOut // index 1
};

switch(fadeOperation.fadeType)
{
    case (FadeManager)0:
    case (FadeManager.fadeIn):
        Debug.Log("Fadein"); //Only this piece of code works
        break;

    case (FadeManager)1:
    case (FadeManager.fadeOut):
        Debug.Log("Fadeout");
        break;

    default:
}

```

As a small caveat, I will make two more points. Firstly, some will argue that you should *always* have a `default:` case to handle any case that does not fall within the above. In cases like this, you can pretty much guarantee that will not happen, so it is more a matter of style. Secondly, in some cases, you can "fall through" cases. For example, if you wanted to run the code in "fadeOut" for "fadeIn" aswell, you could remove the `break;` from "fadeIn" and have your code "fall through" into the next statement. ***You can not do that in C#***, or at least, not in Unity. That said, I feel it might be useful to know that you can do so in other contexts.

## Your Errors

Your primary error actually comes from your understanding of what your doing, and how it should react. The switch, itself, is pretty much solid. That said, there *is* an error in your switch; your `Debug.Log()` statement. I believe you have added this by suggestion, and no one has pointed out the error in your implementation.

### Checking against a private `FadeManager`:

Your logic error falls to the instance of `FadeManager` your trying to check against. In your code, you have a reference to a `FadeManager` array, and a single `FadeManager` inside a `FadeOperations` class. While your array is `public`, your single reference is inside a `private` class reference. Given that this is the only code you have, we can infer that this `private FadeManager _fo` is never changed; being `private` also means you can not change it directly from the inspector.

As a result, you set up your reference as a default value. Since this value has no means to change, it will *always* trigger `case:FadeManager.fadeIn`.

To further test this, simply change `private FadeOperations _fo` to `public FadeOperations _fo`. You should not need to include the `= new FadeOperations()` constructor. While my knowledge on constructor precedence is not perfect, I have confirmed that setting `_fo` to `public` and changing its values in the inspector, the values persist when I play-test.

You can see your code correctly prints its `Debug.Log()` statements, below, where I have simply converted `_fo` to `public`.

## Code inside a `switch` statement must also be inside a `case`

As your code stands, it throws many errors, due to the `Debug.Log()` statement you have added to the inside of your `switch` statement. ***all code*** must correspond to a specific `case`, and as such, many errors will pop up from misinterpretation of the initial `Debug.Log()`. You should place `Debug.Log(_fo.fadeType)` outside of the `switch` statement, or at least enclose it inside a specific `case`.

This appears to be a line added at a later date than your original question, but regardless, it is important to understand that as it is this line will prevent your code from compiling.
> 0 votes

# Answer
public enum JumpState { NormalJump, LongJump}; public JumpState jumpValue; and you can change the value like jumpValue = JumpState.NormalJump;
> -2 votes

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


# Question
Title: Why does my 3d model become invisible as I move the camera away?
I'm trying to load a 3d model from Mixamo:

// let scene = SCNScene(named: "art.scnassets/ship.scn")! let scene = SCNScene(named: "art.scnassets/Ch45\_nonPBR.dae")!

```
    // create and add a camera to the scene
    let cameraNode = SCNNode()
    cameraNode.camera = SCNCamera()
    scene.rootNode.addChildNode(cameraNode)
    scene.fogStartDistance = 10000
    // place the camera
    cameraNode.position = SCNVector3(x: 0, y: 40, z: 100)

    // create and add a light to the scene
    let lightNode = SCNNode()
    lightNode.light = SCNLight()
    lightNode.light!.type = .omni
    lightNode.position = SCNVector3(x: 0, y: 50, z: 10)
    scene.rootNode.addChildNode(lightNode)
    lightNode.light?.intensity = 10000;

    // create and add an ambient light to the scene
    let ambientLightNode = SCNNode()
    ambientLightNode.light = SCNLight()
    ambientLightNode.light!.type = .ambient
    ambientLightNode.light!.color = UIColor.white
    scene.rootNode.addChildNode(ambientLightNode)

    // retrieve the ship node

```

// let ship = scene.rootNode.childNode(withName: "ship", recursively: true)! let ship = scene.rootNode

While the z value for the cameraNode position is 100 or less, I can see the 3d model. But if I increase the value, then the model is no longer visible. Even at 100, parts of the model are not visible.

Is this a problem with lighting or rendering distance ? I would like to move the camera far away so that I can see the whole model on screen. Right now I can only see a part of it. What do I need to change so I can see the whole model clearly like this:

EDIT: I am using Swift 5

# Answer
I do not use swift, but engine Cameras usually work with a `frustum`, which is a special type of collider, almost like a cone away from the camera, that decides what should be drawn and what shouldn't.

Your camera appears to be `culling` (deciding not to draw) things that are far away from it, which suggests to me that the `frustum` is too short.

The camera uses 2 `planes` to decide what the nearest object and furthest object to be drawn is.

These are called `clipping planes`, and it appears to me that your `far clipping plane` (or something similarly named), is too close to the camera.

**Tl;Dr**

Your far clipping plane is likely set too close to the camera, try and find a setting where you can change the far clipping plane of the camera to be further away.
> 2 votes

---
Tags: swift, scenekit
---


# Question
Title: Is Windows window creation faster / more efficient than GLFW window creation?
Are there any benefits to using Windows window for OpenGL or Vulkan rendering, rather than using GLFW window?

Is there any performance hits when using C++ Window creation over GLFW since it provides OpenGL and Vulkan interface?

# Answer
**It depends**

GLFW is just a wrapper around the Windows API calls, so whether you create a window using GLFW or create one using the API, the same calls are ultimately being made.

However, a wrapper such as GLFW can be expected to be robust, to do error-checking, to select optimal formats, and so on, which you may not do if you just wrote the code yourself. So your own code *may* be faster at creating a window, but it *may* also be more likely to do the wrong thing.

At this stage you really need to read the OpenGL wiki Getting Started pages to gain an understanding of the process of initializing OpenGL.

But ultimately, what does it matter? Creating a window is milliseconds at the beginning of your application, and once the window is created OpenGL takes over, so it does not matter how it was created - all other things being equal (pixel formats, hardware acceleration, etc) the performance of OpenGL in your program will be identical.
> 5 votes

---
Tags: opengl, c++, windows, vulkan
---


# Question
Title: Can I make a game based on the Star Wars universe?
I was thinking of trying to make an auto battler using Star Wars characters/ scenes. This game, of course, would be free/ have no intention of monetization in any way.

My guess is this is fine but I want to ask anyway to know if there is anything I should avoid/ know, etc.

Im doing this as a challenge/ personal project to show off to employers when I try to get a job. (Software Engineer)

Thanks

# Answer
> 3 votes
No, you cannot legally do this.

Star Wars is now the intellectual property of Disney. Any reference to named characters, locations, concepts, or other aspects of the universe they've helped popularize, that are not your original creation, would be an unlicensed use of their property.

If Disney's legal team notices your game, it's possible, arguable likely, that it will be targeted for a DMCA takedown, a cease-and-desist notice, or a lawsuit against yourself for infringement on their intellectual property.

tl;dr: If something is not your original creation, and you were not licensed to use it by its creator/owner, then **it is not yours to use in your game**.

The best way to avoid legal trouble is to use only your own original creative works, or those you've paid collaborators to create/use for that purpose.

I would argue that this use of an existing franchise is also not a good portfolio piece, because can read to potential employers as "I lack original ideas of my own, the collaborative spirit to work with other creatives, or a regard for the legal rights of others" — a dangerous combination in a creative industry.

---
Tags: copyright
---


# Question
Title: How to generate random waves for a bullet hell game that feel balanced and natural
My game consists of 'waves' of objects called 'spawners', which once every certain amount of time (their firetime), move to a new place on the screen and spawn an enemy. Each wave has 4 important properties:
1: the amount of spawners the wave has
2: the interval of time between creating new spawners
3: the total length of the wave
4: the types of spawners that can appear in a wave (represented as a `std::vector<std::pair<std::string, int>>` where the string is the spawner name, and the integer is its spawn weight.

The game works by picking a random spawner from the possible spawner types (with a weighted rng) every new spawner interval. Currently waves are set and are loaded from a file at runtime.

My problem is that I cannot find a good way to randomly generate waves that feel balanced and natural. Currently, I am trying to generate waves based on a difficulty value, mostly using weighted random number generation. However, this does not produce balanced waves that correspond well to the target difficulty. Even after trying several different techniques, I am unable to get a system that generates waves that fell balanced and natural (like the ones hand made).

Is there any way to generate waves that feel natural, based off of the difficulty value? How should I approach this problem?

Also if it's of any help, each spawner also defines its own difficulty value.

# **Example Waves:**

**Easier wave:**
SpawnerTypes = {'BasicSpawner': 100} (basic spawner has a difficulty of 10)
SpawnerAmount = 5
NewSpawnerInterval = 4
WaveLength = 30
This is a good easy wave because it the spawner it has is simply shoots bullets that move in one direction at a slow speed, which are easy for the player to dodge. It also does not overwhelm the player with large amounts of them, and the wave is not too long

**Medium Wave**
SpawnerTypes = {'LaserSpawner': 60, 'BasicSpawner': 40} (basic spawner has a difficulty of 10, laser spawner has a difficulty of 20)
SpawnerAmount = 8
NewSpawnerInterval = 3
WaveLength = 30
This is a good medium wave because its combination of spawners requires the player to be paying close attention to multiple parts of the screen other than just right near the character, while still remaining relatively easy. It also spawners more spawners, but balances that by having a small interval between spawners and a small wave length.

**Hard Wave**
SpawnerTypes = {'RicochetSpawner': 100} (ricochet spawner has a difficulty of 60)
SpawnerAmount = 2
NewSpawnerInterval = 10
WaveLength = 30
Note that this wave has only one spawner type and only 2 of them, but is still much harder than the other listed waves This wave is hard because the spawner it contains is challenging to keep track of, and in large numbers quickly because almost impossible, so it only spawners two spawners. However, the wave still lasts for 30 seconds, which provides the player with a decent challenge while not completely overwhelming them.

**Extremely Challenging Wave** SpawnerTypes = {'RandomSpawner': 30, 'LoopSpawner : 70} (random spawner has a difficulty of 90, loop spawner has a difficulty of 60)
SpawnerAmount = 4
NewSpawnerInterval = 5
WaveLength = 40
This wave is a perfect example of a wave which is extremely challenging, but is possible for a skilled player. It has two very hard spawners, one of which is very unpredictable (hence the name 'random'). It also spawns 4 spawners, and the wave lasts a total of 20 seconds longer than when the last spawners is created

# Answer
> 1 votes
One of the most rigorous ways to ensure that a procedurally generated wave, or other form of procedurally generated levels is balanced to a particular standard is to use automated testing. When you make a wave, you (quickly) run an AI through it, with the reaction times and level of spatial awareness that you want the player to need, and if the AI can't beat the wave, you throw that wave away and generate a new one. I've only seen this approach actually done a small handful of times, most people prefer to just tune their generators by ear until they get something that's generally good enough.

Waves in bullet hells usually look geometrically interesting, so I think making things look more "natural" might mostly just come down to placing your spawners according to interesting math.

---
Tags: c++, procedural-generation, random
---


# Question
Title: Running Unity development build in Android emulator without signing
I am working on project with a friend who uses Windows while I am using Ubuntu. We are using Unity collaborate and it's going fine except when we want to build.

The keystore is in his filesystem, `D:/Programs -Work/Game Dev/Keystore/user.keystore` and I can't replicate his path.

Also, when I try to do a development build and run, it fails because Unity says the apk isn't signed, contrary to this article which says that development builds do not need to be signed.

So this leads to two questions:

1. Is there any way to build from both devices?
2. Is there any way to emulate the game on android emulator?

# Answer
> 1 votes
> Ans Q1:

Yes, you can build for both devices but you have to assign Keystore for each device or you could just disable the Custom Keystore option inside

> Player settings -\> Publishing settings -\> Custom Keystore -\> Uncheck box. Like this:

**Warning:** If you uncheck custom Keystore then you would not be able to publish this APK to any store but of course, you could test it on your device. And later when you want to publish it then just Enable Custom Keystore and assign the Keystore you want to assign.

> Ans Q2: Yes, you could emulate this on the Android emulator. like Nox Player. or Any other.

---
Tags: unity, tools, debugging, build-process
---