# Question
Title: How can I decelerate a physics object to a stand still?
I am currently working on a little prototype and I am struggling to apply a friction force to slow down the player object.

I have a simple physics engine using the model of setting acceleration, which then is applied to the velocity before being applied to the position. To calculate the friction, before the acceleration is applied to the velocity, I multiply the velocity by -1 to the the opposite direction, then scale the magnitude by 0.5. I then apply this force to the acceleration by adding it to the existing acceleration.

This doesn't seem to work however, and the object just moves back and forwards erratically.

```

    constructor (x, y){
        this.r = 20;
        this.position = new Vector2(x, y);
        this.velocity = new Vector2(0, 0);
        this.acceleration = new Vector2(0, 0);
        this.maxSpeed = 2.3;
        this.friction = 0.5;
        this.createSprite();
        this.addForce(new Vector2(-5, 1));

    }

    createSprite(){
        let sprite = new PIXI.Graphics();
        sprite.beginFill(0xFF0000);
        sprite.lineStyle(5, 0xBB0000, 1);
        sprite.drawCircle(0, 0, this.r);
        sprite.endFill();

        this.sprite = sprite;
        this.sprite.position = this.position;
        app.stage.addChild(this.sprite);

    }

    move(){
        //this.calcFriction();
        this.velocity = this.velocity.add(this.acceleration); //apply acceleration to velocity
        this.limitVel();
        this.vel

        this.position = this.position.add(this.velocity);

        this.sprite.position = this.position;

    }

    limitVel() {
        let mag = this.velocity.magnitude();
        if(mag > this.maxSpeed){
            this.velocity = this.velocity.setMag(this.maxSpeed);
        }
    }

    addForce(force) {
        this.acceleration = this.acceleration.add(force);
    }

    calcFriction(){
        let negVel = this.velocity.scale(-1);
        let frictionForce = negVel.scale(this.friction);
        this.addForce(frictionForce);
        console.log(this.acceleration);

    }

}

```

This is the code I have written so far. The move function is called every frame.

I feel like there is one simple but important concept I'm missing here.

Thanks.

# Answer
`I multiply the velocity by -1 to the the opposite direction`

That's your mistake. If you do that, you then have to check if you have gone into reverse.

Easier ways focus on scalar rather than vector arithmetic, as it's cheaper and easier to reason about.

**Friction** works as follows:

```
const FRICTION = 0.1;
let speed = velocityVector.magnitude();
let speedReduced = speed - FRICTION;
if (speedReduced < 0)
{
    speedReduced = 0;
}
velocityVector.normalise(); //same as velocityVector.divide - results in length 1.0
velocityVector.multiply(speedReduced);

```

**Damping** brings the value close to zero, arithmetically:

```
const DAMPING = 0.98;
let speed = velocityVector.magnitude();
let speedDamped = speed * DAMPING;

velocityVector.normalise(); //same as velocityVector.divide - results in length 1.0
velocityVector.multiply(speedDamped);

```

...this will get very close to zero, but takes a very long time to reach actual zero, so stopping *entirely* is thus done by adding a logical IF into the above:

```
const EPSILON = 0.01;
const DAMPING = 0.98;
let speed = velocityVector.magnitude();
let speedReduced = speed * DAMPING;

if (speedReduced < EPSILON)
    speedReduced = 0;

velocityVector.normalise(); //same as velocityVector.divide - results in length 1.0
velocityVector.multiply(speedReduced);

```

**Comparison**

Multiplication may be preferred over subtraction as you technically don't *need* the explicit check to see if you are close to zero... you *can* just let the object sit and continue to be processed at miniscule velocities. But most implementations would include the close-to-zero check.

Note that friction provides a linear reduction in speed, unlike damping - depends what you prefer. The conditional there is mandatory, or else you will start going backwards.
> 1 votes

---
Tags: physics, game-mechanics, physics-engine
---


# Question
Title: Finding the closest point on a concave mesh
One of my game systems requires that I find the closest point on a generalized mesh, which more often than not will be concave. This prevents me from just using Unity's built in `ClosestPoint` function, and all other alternatives have some other caveat which prevents me from using them so far.

The meshes are dynamically generated, pretty complex, and altered often, so it would be computationally unreasonable to split it into multiple convex meshes, unless there's some way I don't know about which allows fast splitting/reattachment of said meshes.

I considered checking a sphere around the point, and increasing the size of that sphere until I get a collision, but `OverlapSphere` and `CheckSphere` don't give any means to check the point of collision, only to check whether there was a collision at all.

Continuing with that train of thought, I tried a `Spherecast` with the same method and the maximum distance set to zero, but that didn't work either. `Spherecasts` don't detect any objects which are inside of the starting sphere location, so setting the distance to zero will result in no collision every time.

As a workaround to that, I tried setting the distance to a small positive number, equal to the step size which the `Spherecast` increases by each pass (in my case, 0.2). This almost works, but causes the cast to only detect collision points if I have a general direction to give it. There are two ways I tried to resolve this:

The first is by just passing in the direction from the point towards the center of the mesh I am trying to find collisions with, and although this works for a sphere, it breaks down for most of my other test cases, and just in a lot of different scenarios (Very concave polyhedra and shapes such as torii being two examples of situations where this method does not work.)

The second method I tried was to just take the direction to the closest point on the last frame, and pass that into the `Spherecast`. Again, works in some situations, but breaks down on large dihedral angles. Neither of these are really sufficient for what I need them for.

In terms of the constraints which I have to work under, the point should always be on the outside of the mesh, and the point should never be too far away from the mesh, but other than that there isn't really much else I can guarantee. Both the shape and the topology of the mesh are subject to change over time.

# Answer
> 1 votes
We know that the closest point on a given triangle can't be any further away than the closest of its vertices.

But it could be *closer* than the closest vertex, so we need to use some knowledge of our mesh structure to make some better estimates here. For instance, if you have a maximum bounding radius the triangle would ever have.

1. Iterate over your vertices and store the distance of that vertex from your point.

Store the smallest such distance you find as your best candidate.
2. Iterate through your triangles and, if the triangle has no vertex closer than this best candidate distance plus your bounding radius, skip over it.
3. For each remaining triangle, find the closest point within that triangle and update your best candidate to keep the closest one you find.

If you can, try storing your mesh in some type of acceleration structure like an octree so you can quickly find a subset of the vertices & triangles worth testing, and discard most of the mesh from consideration.

# Answer
> 1 votes
```
public static bool CheckSphereExtra(Collider target_collider,SphereCollider sphere_collider,out Vector3 closest_point,out Vector3 surface_normal)
{
    closest_point = Vector3.zero;
    surface_normal = Vector3.zero;
    float surface_penetration_depth = 0;

    Vector3 sphere_pos = sphere_collider.transform.position;
    if (Physics.ComputePenetration(target_collider,target_collider.transform.position,target_collider.transform.rotation,sphere_collider, sphere_pos, Quaternion.identity,out surface_normal,out surface_penetration_depth))
    {
        closest_point = sphere_pos + (surface_normal * (sphere_collider.radius - surface_penetration_depth));

        surface_normal = -surface_normal;

        return true;
    }

    return false;
}

```

This will find the closest point and normal to the center of a sphere collider as long as the colliders are intersecting (make the radius large). Works with all types of colliders as far as I know. You can place the sphere collider into a "No collision" layer so it won't physically collide with anything or possibly make it a trigger.

---
Tags: unity, c#, collision-detection, 3d-meshes
---


title: Libgdx music is not working properly

text:
# Question
Title: Libgdx music is not working properly
I finished my game programming but I have small problem, please help me I want to finish it completely. I am starting background music when the user goes to the PlayScreen and when the kid in the game dies, the background music stops and starts game over music and move to game over screen, then the user goes to the menu screen and choose the level he wants then go back to the PlayScreen but the back music isn't working again, I didn't know how to solve it although the music is working very well when start the game and when the user win the level, but it is not working when the kid dies. here is the code where I stop the music in the kid class:

```
public State getState()
    {
        //Gdx.app.log(Float.toString(b2body.getLinearVelocity().x),"hi");
        if ((Hud.getTime()<0)) {
            Fruits.manager.get("music/Backmusic.ogg", Music.class).stop();
            Fruits.manager.get("music/fail.mp3", Sound.class).play();
            collectoIsDead=true;
            Filter filter = new Filter();
            filter.maskBits = Fruits.NOTHING_BIT;
            for (Fixture fixture : b2body.getFixtureList())
                fixture.setFilterData(filter);
            b2body.applyLinearImpulse(new Vector2(0, 5f), b2body.getWorldCenter(), true);
            //b2body.applyLinearImpulse(new Vector2(0,-2.5f), b2body.getWorldCenter(), true);
            Hud.setTime();// to prevent the action of applying more times

            return State.DEAD;
        }
        if ( Rockhit()) {
            Fruits.manager.get("music/Backmusic.ogg", Music.class).stop();
            Fruits.manager.get("music/fail.mp3", Sound.class).play();
            collectoIsDead=true;
            Filter filter = new Filter();
            filter.maskBits = Fruits.NOTHING_BIT;
            for (Fixture fixture : b2body.getFixtureList())
                fixture.setFilterData(filter);
            b2body.applyLinearImpulse(new Vector2(0, 5f), b2body.getWorldCenter(), true);
            //b2body.applyLinearImpulse(new Vector2(0,-2.5f), b2body.getWorldCenter(), true);
            return State.DEAD;
        }
        if((Hud.getTime()==0&& Hud.getScore()>=(level*30)+50)|| (Hud.getScore()>=(level*30)+50)) {
            Fruits.manager.get("music/Backmusic.ogg", Music.class).stop();
            Fruits.manager.get("music/cheering.mp3", Sound.class).play();
            return State.SUCCESS;
        }
        if (b2body.getLinearVelocity().x!=0)
            return State.RUNNING;
        else
            return State.STANDING;
    }

```

And here is the code where I start the music in the constructor of the PlayScreen:

```
public PlayScreen(Fruits game, float level)
    {
        this.level=level;
        this.game=game;
        gamecam=new OrthographicCamera();

        gameport=new FitViewport(Fruits.V_WIDTH/Fruits.PPM,Fruits.V_HIEGT/Fruits.PPM,gamecam);

        hud=new Hud(game.batch,level);
        atlas=new TextureAtlas("mypack.pack");
        mapLoader=new TmxMapLoader();

            map=mapLoader.load("world10.tmx");

        renderer=new OrthogonalTiledMapRenderer(map,1/Fruits.PPM);
        gamecam.position.set(gameport.getWorldWidth()/2,gameport.getWorldHeight()/2f,0);
        globalcounter=100;
        world=new World(new Vector2(0,-10),true);
        b2dr=new Box2DDebugRenderer();
        new B2WorldCreator(this);
        player=new Collector(world,this,level);
        world.setContactListener(new WorldContactListener());
        controller=new Controller(game.batch);

        music=Fruits.manager.get("music/Backmusic.ogg", Music.class);
        music.setLooping(true);
        music.play();
    }

```

# Answer
The best way to load in music and sound effects resources is through LibGDX's audio methods:

```
Music music = Gdx.audio.newMusic(Gdx.files.internal(path_to_music_file));
Sound sound = Gdx.audio.newSound(Gdx.files.internal(path_to_sound_file));

```

To play the music:

```
music.setVolume(1f);
music.play();

```

To play the sound effect:

```
long id = sound.play();
sound.setVolume(id, 1f);

```

It is best practice to isolate your resources from the rest of the model. You may or may not have done this yet - I can't judge from your code - but it is best to create a resource handler, which stores resources (textures, music, sound) locally (e.g. in HashMaps dedicated to each type of resource), and which enables you to load them all from one source later. An example of such a resource handler may be:

```
public class ResourceHandler {

    //HashMaps for storing resources
    private HashMap<String, Texture> textures;
    private HashMap<String, Music> music;
    private HashMap<String, Sound> sounds;

    public ResourceHandler() {
        textures = new HashMap<String, Texture>();
        music = new HashMap<String, Music>();
        sounds = new HashMap<String, Sound>();
    }

    public void loadTexture(String path, String key) {
        Texture texture = new Texture(Gdx.files.internal(path));
        textures.put(key, texture);
    }

    public void loadMusic(String path, String key) {
        Music musicfile = Gdx.audio.newMusic(Gdx.files.internal(path));
        music.put(key, musicfile);
    }

    public void loadSound(String path, String key) {
        Sound soundfile = Gdx.audio.newSound(Gdx.files.internal(path));
        sounds.put(key, soundfile);
    }

    public Texture getTexture(String key) {
        return textures.get(key);
    }

    public Music getMusic(String key) {
        return music.get(key);
    }

    public Sound getSound(String key) {
        return sounds.get(key);
    }

}

```

If doing this, there should be no problems with playing sounds or music, provided that the file you're loading in is actually functional.
> 4 votes

# Answer
If you want repetitive music, use:

```
music.setLooping(true);

```

after

```
music.play();

```
> 0 votes

---
Tags: java, android, libgdx
---


# Question
Title: transform.position returning wrong value (UNITY 2D)
I am trying to place the ball on the paddle until a key is pressed, also there is box collider that triggers if the ball falls down. For some reason the transform.position.y of the ball gameObject is going below zero while the ball is still stuck to the paddle in the game and therefore triggering the collider unnecessarily . Attaching code of paddle and ball bellow .

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

public class ballScript : MonoBehaviour
{
    [SerializeField] GameObject myPaddle;
    Vector3 paddleToBallVector;
    void Start()
    {
        paddleToBallVector = transform.position - myPaddle.transform.position;
        lockToPaddle();
    }
    void Update()
    {
        lockToPaddle();
    }

    private void lockToPaddle()
    {
        transform.position = myPaddle.transform.position + paddleToBallVector;
    }
}

```

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

public class paddleScript : MonoBehaviour
{
    [SerializeField] float screenWidthUnits = 16f;
    [SerializeField] float paddleLeftLimit = 1.07f;
    [SerializeField] float paddleRightLimit = 14.928f;

    void Update()
    {
        float screenWidthPercentage = Input.mousePosition.x / Screen.width;
        Vector2 curPaddlePos = new Vector2(screenWidthPercentage * screenWidthUnits, transform.position.y);
        curPaddlePos.x = Mathf.Clamp(curPaddlePos.x, paddleLeftLimit, paddleRightLimit);
        transform.position = curPaddlePos;
    }
}

```

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

public class bottomCollisionScript : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log(collision.gameObject);
        Debug.Log("Game Over");
    }
}

```

# Answer
> 1 votes
I found what i did wrong , It was because I used transform to position a Object that had a rigid body. The RigidBody component causes the object to be subject to Physics Laws and trying to reposition it using transform didn't stop factor like gravity acting on it.

# Answer
> 0 votes
In the ball script you need to call

```
paddleToBallVector = transform.position - myPaddle.transform.position;

```

in the `Update` method and not in `Start`, before you call `lockToPaddle`. That is because the paddle might be moving in the mean time.

Should note that this is not the proper solution as this can cause the ball to get inside the collider of the paddle. Instead you should you should use a RigidBody2D and apply a force.

---
Tags: unity, c#, collision-detection, game-component
---


title: Detect which monitor an SDL window uses

text:
# Question
Title: Detect which monitor an SDL window uses
I have some SDL code that, before creating a Window and a Renderer, detects the display DPI using `SDL_GetDisplayDPI`, to properly scale textures late on for different types of monitors (for instance my MacBook Pro's monitor returns a DPI of 258, while my external Dell monitor returns 93).

When I use 2 monitors, `SDL_GetNumVideoDisplays` properly returns 2, but I couldn't find any function in SDL that would get me which monitor the window is running in, to call `SDL_GetDisplayDPI` with the correct index, nor any way to detect when the window is dragged from one monitor to the other.

Is there a way to do those things in SDL, or is there a tutorial somewhere that would explain how to do that (hopefully in a platform-independent way)?

# Answer
> 1 votes
I think you want `SDL_GetWindowDisplayIndex`. It takes in a pointer to your `SDL_Window` and returns the display index where the center of that window lies.

As to handling dragging, you probably have to manually requery this index yourself while handling resize events inside the event loop.

---
Tags: sdl2
---


# Question
Title: How to use assimp textures with openGL/getting a better understanding
I recently learned how to load a model to openGL using assimp, but I am having trouble figuring out how to do lighting calculations on this model. Previously with my own created objects I would set the normals manually and pass them to the shader as attributes. Then I would use one diffuse and one specular texture passed as uniforms for lighting.

I'm trying to do the same with a model, but I can't seem to get it to behave correctly. When I use my own objects everything works normally, but when I try to draw the model some weird lighting occurs.

Here's how the model should look:

But mine looks like this:

What confuses me in particular is that assimp loads both normal vertices and normal textures. I'm not sure what the difference between them is or if there is more about model loading that I've yet to learn, which is entirely possible since I don't know much about heightmaps and other things yet.

Anyway, here's what I'm doing for calculations:

```
void main()
{
    vec3 normal = normalize(Normal);
    vec3 viewDir = normalize(viewPos - fragPos);

    vec3 result;

    for (int j = 0; j < sizeModels; j++)
        result += CalcDirLight(DirLights, normal, viewDir, models[j]);

    FragColor = vec4(result, 1.0);
}

vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir, Material textures)
{
    vec3 lightDir = normalize(-light.direction);
    // diffuse shading
    float diff = max(dot(normal, lightDir), 0.0);
    // specular shading
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), textures.shininess);
    // combine results
    vec3 ambient = light.ambient * vec3(texture(textures.diffuse, Tex));
    vec3 diffuse = light.diffuse * diff * vec3(texture(textures.diffuse, Tex));
    vec3 specular = light.specular * spec * vec3(texture(textures.specular, Tex));
    return (ambient + diffuse + specular);
}

```

Notice that I'm providing my own diffuse values to the DirLight struct. The Material struct is what contains the diffuse and specular textures, as well as a shininess float.

For reference I am following guides from this site: https://learnopengl.com/

Any help would be appreciated!

# Answer
Turns out the idea of adding every mesh's texture into a single fragment was unnecessary. Each individual mesh already contained its own textures, so drawing them individually allows for the same result.

Changes on the fragment shader:

```
void main()
{
    vec3 viewDir = normalize(viewPos - FragPos);
    vec3 Normalized = normalize(Normal);

    // Now a single result. Function no longer needs the fourth parameter since it just accesses the single uniform struct instead of an array of structs.
    vec3 result = CalcDirLight(DirLights, Normalized, viewDir);

    FragColor = vec4(result, 1.0);
}

```

I am still unsure how this compares to my original idea performance-wise, but this is definitely makes more sense logically.
> 1 votes

---
Tags: opengl, models, 3d-modeling, assimp
---


# Question
Title: How to apply saturn's ring texture in Unreal Engine 4?
I'm working on a "solar system" model project. And while trying to apply saturn's ring texture which is this one :

it ended up looking like this:

I'm new to UE4 and this branch in general. So I have no idea how to fix this . your help would be appreciated

# Answer
In order to obtain the best result for your project, there is basically two ways:

* Make your own 3D models from scratch with a 3D software like **Blender** (free)/ **Maya LT**/ **3DS Max**.
* download free 3D models from various websites (I personally do not rely on this solution so I don't know if these websites will be good, but you can always download models from **Clara.io** or **CGTrader**).

If you want to make the 3D Model from scratch, you will need to model the Rings of Saturn and **unwrap** the **UVs** (that's the main problem in your result), and either create the texture from scratch (with **Blender**, **Substance** or another Texture Software) or apply the texture that you've uploaded here.

Please note that your current texture of the Rings of Saturn will be displayed in *Unreal Engine*, but it is definitely not the right format in the gaming industry (i.e., the resolution of your file is not a **Power of Two** like **256\*256** or **1024\*1024**). The various reasons of keeping a Power of Two texture might not ring a bell at this stage but should be kept in mind (mip-maps, no GPU optimization, no multi-plaform game support...).

If Blender will be your choice for the 3D Software (and Texture Software), you can watch some YouTube tutorials for beginners, like **Blender Guru** or **Grant Abbitt**.

Good luck with your Solar System project!
> 0 votes

---
Tags: textures, unreal-4, blender, 3d-meshes, unreal
---


title: Basic rigidbody movement

text:
# Question
Title: Basic rigidbody movement
This is a noob question but, what is the rigidbody movement equivalent of:

```
transform.position += transform.right * speed * Time.deltaTime;

```

# Answer
> 0 votes
It's:

```
Vector3 newPosition  = transform.position
                     + transform.right * speed * Time.deltaTime;

rigidbody.MovePosition(newPosition);

```

or

```
rigidbody.velocity = transform.right * speed;

```

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


# Question
Title: Unity difficulty placing text within the reference resolution of the canvas
I have a TextMeshPro GameObject, which I placed within the Canvas. The canvas is set to `Scale with Screen Size` and has a reference resolution of 1440x1080.

The TextMeshPro GameObject is anchored to the top-right and its position horizontally is -185 from the anchored point (top-right). And within 1440x1080 resolution it looks like:

But when I make my Display resolution higher or smaller (like for example 1920x1080 as in the image below), the TextMeshPro GameObject goes outside game and ends up in the black area.

I tried changing the position of TextMeshPro GameObject via a script attached to the canvas. I came up with the following formula but it seems wrong.

`DisplayResolution.x - (DisplayResolution.X + (ReferenceResolution.X - TextMeshPro.Location.X))`

Assuming:

`DisplayResolution.X` = 1920
`ReferenceResolution.X` = 1440
`TextMeshPro.Location.X` = -185

**Edit - answer to comments:**

Where Starry Backfield is at:

Camera settings:

Canvas Settings:

# Answer
> 1 votes
Ah, the joy of creating resolution-responsive screen layouts in Unity.

If I understand you correctly, your goal is to create an UI which always preserves its aspect ratio, but also fills as much of the screen as possible, letterboxing or pillarboxing as necessary.

If that is the case:

1. If your canvas itself has a Canvas Scaler component, remove it.
2. Add a new empty game object to the canvas (let's call it "Content").
3. Set the anchor preset in the "Content" to "Stretch" in both directions
4. Resize the "Content" to fill the whole canvas.
5. Add an "Aspect Ratio Fitter" to "Content". Set its Aspect Mode to "Fit In Parent" and its "Aspect Ratio" to the ratio of width to height you want it to maintain.
6. Add your UI elements as children of "Content". Make sure their anchors are the corners you want them to stay relative to. For example, if you want your score text to always stay in the upper right corner, set its anchor to upper right and drag it into the upper right corner.
7. \[optional\] Do you want the elements in "Content" themselves to shrink or enlarge with different screen sizes so they don't overlap on low resolutions and don't become too small on large resolutions? Then add a "Canvas Scaler" to "Content". Set its UI Scale Mode to "Scale With Screen Size" and its Screen Match Mode to "Expand".

Your UI should now behave as described.

Now the next challenge would be to get the rendering of the actual game to behave the same way as the canvas and letterbox/pillarbox as the resolution requires. But that's outside of the scope of this question.

4:3 aspect ratio:

Landscape aspect ratio:

Portrait aspect ratio:

---
Tags: unity, 2d, mathematics, screen, aspect-ratio
---


title: FindObjectsOfType returns null array

text:
# Question
Title: FindObjectsOfType returns null array
I am making the game in this tutorial: https://www.youtube.com/watch?v=OR0e-1UBEOU

and at 2:53:23 he is coding a LevelController script. I noticed that mine wasn't working the way his was and so I went to try and debug the error. I found that the error was in the function FindObjectsOfType(); You can find my code below.

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

public class LevelController : MonoBehaviour
{
    private Enemy[] _enemies;

    private void onEnable()
    {
      _enemies = FindObjectsOfType<Enemy>();
    }

    // Update is called once per frame
    void Update()
    {
      Debug.Log(_enemies);
    }
}

```

When I run this my debug log returns null values which is confusing because I have 3 objects (Monster, Monster (1) and Monster (2)) which have the Enemy script assigned to them.

What could be going wrong?

# Answer
I think it might be a typo.

You have a method named `onEnable`. This should be `OnEnable` (Capital O).

You can see all the methods that MonoBehaviour supports here: https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
> 2 votes

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


# Question
Title: I have a menu with Textbutton but the buttons do not respond to the mouse
public class MainMenuGameScreen extends BaseScreen {

```
Texture charmander;
Texture button;
Skin skin;
Skin alternativa;
private ActorJugador charmandera;
private Actorcubo prota;
Animation animacione;
ArrayList<Sprite>animacion;
Music song;

@Override
public void initialize() {
    song = Gdx.audio.newMusic(Gdx.files.internal("music/Megalovania.mp3"));
    song.setLooping(true);
    song.setVolume(0.3f);
    song.play();
    animacion=new ArrayList<>();
    animacion=meterSprite(animacion);
    charmander=new Texture("charmader.png");
    button=new Texture("personaje0.png");

    BaseActor fondo=new BaseActor(0, 0, mainStage);
    fondo.setSize(800, 640);
    crearSkins();
    alternativa=new Skin(Gdx.files.internal("craftacular/skin/craftacular-ui.json"));
    Label titulo = new Label("GEOMETRY DASH", alternativa);
    uiTable.add(titulo).center().width(250).height(120).pad(5);
    BaseActor background = new BaseActor(0, 0 , mainStage);
    TextButton button1 = new TextButton("nivel 1", skin);
    button1.addListener(new ClickListener() {
        public void clicked(InputEvent event, float x, float y) {
        Geometry.setActiveScreen(new Nivel1());
        pause();
        }
    });

    uiTable.row();
    uiTable.add(button1).center().width(250).height(100).pad(5);
    TextButton btn2 = new TextButton("nivel 2", skin);
    btn2.addListener(new InputListener() {
        public void clicked(InputEvent event, float x, float y) {
            //  CrazyJumper.setActiveScreen(new LevelScreen2());

            pause();
            }
        });

    uiTable.row();
    uiTable.add(btn2).center().width(250).height(100).pad(5);
    TextButton btn3 = new TextButton("nivel 3", skin);
    button1.addListener(new ClickListener() {
        public void clicked(InputEvent event, float x, float y) {
        //  CrazyJumper.setActiveScreen(new LevelScreen1());
            System.out.println("nivel 3");
            pause();
        }
    });

    uiTable.row();
    uiTable.add(btn3).center().width(250).height(100).pad(5);

    TextButton btnsalir = new TextButton("salir", skin);
    btnsalir.addListener(new ClickListener() {
        public void clicked(InputEvent event, float x, float y) {
        //  CrazyJumper.setActiveScreen(new LevelScreen2());.
            pause();

        }
    });
    uiTable.row();
    uiTable.add(btnsalir).center().width(250).height(100).pad(5);
    uiTable.row();
    mainStage.addActor(uiTable);

}
private ArrayList<Sprite> meterSprite(ArrayList<Sprite> animacion2) {

    Sprite sprite1=new Sprite(new Texture(Gdx.files.internal("personaje0.png")));
    Sprite sprite2=new Sprite(new Texture(Gdx.files.internal("personaje1.png")));
    Sprite sprite3=new Sprite(new Texture(Gdx.files.internal("personaje2.png")));
    Sprite sprite4=new Sprite(new Texture(Gdx.files.internal("personaje3.png")));
animacion2.add(sprite1);
animacion2.add(sprite2);
animacion2.add(sprite3);
animacion2.add(sprite4);

    return animacion2;
}
private void crearSkins() {
    //creando fuente
    BitmapFont font=new BitmapFont();
    skin=new Skin();
    skin.add("default", font);
    //creando textura
    Pixmap pixmap=new Pixmap(Gdx.graphics.getWidth()/4, Gdx.graphics.getHeight()/10, Pixmap.Format.RGB888);
    pixmap.setColor(Color.WHITE);
    pixmap.fill();
    skin.add("background", new Texture(pixmap));
    //estilo del boton
    TextButton.TextButtonStyle estilo=new TextButton.TextButtonStyle();
    estilo.up=skin.newDrawable("background",Color.GRAY);
    estilo.down=skin.newDrawable("background",Color.DARK_GRAY);
    estilo.checked=skin.newDrawable("background",Color.DARK_GRAY);
    estilo.over=skin.newDrawable("background",Color.BLUE);
    estilo.font=skin.getFont("default");
    skin.add("default", estilo);

}
public void show() {
    mainStage=new Stage();
    prota=new Actorcubo(button);
    charmandera=new ActorJugador(charmander);
    mainStage.addActor(prota);
    mainStage.addActor(charmandera);
    mainStage.addActor(uiTable);

    charmandera.setPosition(500, 200);
    prota.setPosition(100, 200);

}
public void pause() {
    song.pause();
}

@Override
public void update(float dt) {

}
public void hide() {
    mainStage.dispose();
    charmander.dispose();
}

public void render(float delta){
    Gdx.gl.glClearColor(0.4f, 0.5f, 0.8f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    mainStage.act();
    comprobarColision();
    mainStage.draw();
}
private void comprobarColision() {
    if ((prota.getX() +prota.getWidth())>charmandera.getX()&&(prota.isAlive())) {
        System.out.println("colision");
        prota.setAlive(false);
    }

}

```

}

# Answer
You should define the input processor for the screen:

```
Gdx.input.setInputProcessor(stageInstance);

```
> 1 votes

---
Tags: libgdx
---


# Question
Title: Exporting prefab includes a lot of unneccessary asset dependencies
I just exported one of my assets into a `unitypackage`. It included all dependencies very nicely so I can use them.

Then I tried another prefab, but it included a lot of unrelated assets from all over the project. This is a very simple prefab and I don't know how the clutter is considered to be dependencies.

When I click "show dependencies" it brings up the clutter in the project menu. There should be no clutter dependencies whatsoever. It really isn't that complex of a prefab.

I also double checked the prefab elements to see if any of them are somehow using the said clutter, they aren't.

How can this happen? Is there a way to solve it (other than selective clicking in export menu)?

# Answer
> 1 votes
Okay, found the solution. One of my elements had a script on it.
So that script was calling other scripts, which resulted in a spider web of dependencies, which also included a lot of seemingly unrelated assets.

I just exported the asset without the script and carried over the said script manually.

My scripts are pretty connected I guess.

I'm still open to better solutions if any.

---
Tags: unity, assets, export
---


# Question
Title: Directory.CreateDirectory() created a folder with name that was supposed to be a file
i am experiencing some problem here , i have a path :

"/folder/folderagain/file.xml"

i tried to use Directory.CreateDirectory() to create all folder (in case one of them is missing) and then reuse the path to create a file in another place inside the script. But instead a folder named "file.xml" was created by Directory.CreateDirectory() and my script got blocked from creating the file .

I managed to solve this problem by creating 2 different path , one of them end with file.xml and the other does not. But is there any better way to do it ? can i tell Directory.CreateDirectory() to create only folder ??

look at screenshot below , there's System.UnautorizedAccessException error because my script trying to create file named "keymap.xml" but a folder with the exact name already exist so it thrown that error .

# Answer
> 0 votes
Use `Path.GetDirectoryName()` to get everything except the last segment of the path, which is filename in your situation.

---
Tags: unity, c#, xml, path, filestream
---


title: What are the capabilities of Panda3D?

text:
# Question
Title: What are the capabilities of Panda3D?
1. Can Panda3D game be served from cloud such as AWS ?
2. Can Panda3D be used for mobile game development (iOS, Android) ? I'm aware Unity can be used but what about Panda3D ?

# Answer
> 1 votes
Member of the community called Yonnji confirmed that Panda3D game indeed can be served from a cloud provider: https://discourse.panda3d.org/t/panda3d-running-from-cloud-mobile-game-development/26039/4

Secondly, speaking of deployment to Android. There's a port to Android however as the snippet from official docs say deployment on Android is quite a struggle at the moment but looks like devs are working hard to make it easier for the future.

> Android port
>
> The new release has made significant strides towards bringing the Android port to the level of quality one should expect of a Panda port. It’s now even possible to compile Panda3D on your Android machine, and there is even a third-party development environment available on the Play Store for developing Python games on your Android device. The major shortcoming as of yet is that there is no easy deployment pipeline yet to deploy your games for Android, so that will be a major priority going forward.

Sadly, no mention of support for iOS.

---
Tags: panda3d
---


# Question
Title: How to perform alpha blending on saved raw argb videos(a image and a video will also work) using direct3d9 , direct3d10 or direct3d11?
I'm trying to perform alpha blending on videos using direct3d11. I've wrote the code snippet below to achieve this. I've tried to read the video file out2.argb frame by frame and store it in the rawData. Later, I passed that rawData to CreateTexture2D but pTexture remained null after the execution of the API. So I tried passing NULL to the CreateTexture2D and passing rawData to the UpdateSubresource but again the pTexture remained NULL.

HRESULT result;
    FILE * fp = NULL;
    int size = 1280 * 720 * 4 ;
    void * rawData = NULL;
    D3D11_TEXTURE2D_DESC desc;
    desc.Width = 1280;
    desc.Height = 720;
    desc.MipLevels = 0;
    desc.ArraySize = 1;
    desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    desc.SampleDesc.Count = 1;
    desc.Usage = D3D11_USAGE_DYNAMIC;
    desc.BindFlags = D3D11_BIND_SHADER_RESOURCE| D3D11_BIND_RENDER_TARGET;
    desc.CPUAccessFlags = 0;
    desc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;

    D3D11_SHADER_RESOURCE_VIEW_DESC shader;
    shader.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    shader.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    shader.Texture2D.MipLevels = -1 ;
    shader.Texture2D.MostDetailedMip = 0;

    fp = fopen("../Engine/Data/out2.argb", "rb");
    rawData = malloc(size);

    D3D11_SUBRESOURCE_DATA data;
    data.SysMemPitch = 1280 * 4;
    data.SysMemSlicePitch = 1280 * 720 * 4;

    if (NULL == rawData)
        return -1;
    int row_pitch = (1280 * 4) * sizeof(unsigned char);
    if (fp)
    {
        /*while (!feof(fp))
        {*/
            fread(rawData, size,1, fp);
            //D3D11_SUBRESOURCE_DATA *sSubData = new D3D11_SUBRESOURCE_DATA[1];
            //for (int i = 0; i < 1; i++) {
            //  sSubData[i].pSysMem = rawData;
            //  sSubData[i].SysMemPitch = (UINT)(1280 * 4);
            //  sSubData[i].SysMemSlicePitch = /*(UINT)(1280 * 720 * 4)*/0;
            //}

            //data.pSysMem = rawData;
            // GOT FRAME
            device->CreateTexture2D(&desc, NULL, &pTexture);
            deviceContext->UpdateSubresource(pTexture, 0, NULL, rawData, row_pitch , 0);
            result = device->CreateShaderResourceView(pTexture, &shader, &m_texture);
            if (FAILED(result))
            {
                return false;
            }

    /*  }*/

        fclose(fp);
        fp = NULL;
        free(rawData);
        return true;
```
</code></pre>

# Answer
> 1 votes
https://docs.microsoft.com/en-us/windows/win32/api/d3d11/ne-d3d11-d3d11\_usage

> ## Resource Bind Options
>
> **Dynamic**: Input to a Stage: yes³
>
> 3 - The resource can only be created with a single subresource. The resource cannot be a texture array. The resource cannot be a mipmap chain.

---

Dynamic resources cannot be mipmap chains, so create your texture without mipmaps:

```
D3D11_TEXTURE2D_DESC desc;
desc.MipLevels = 1;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.MiscFlags = 0;

```

---

You have two further problems with the above.

1. You're not filling in all members of the D3D11\_TEXTURE2D\_DESC struct; you also need to initialize desc.SampleDesc.Quality to 0.
2. For a dynamic texture, you need to set desc.CPUAccessFlags.

So your final, working, D3D11\_TEXTURE2D\_DESC struct will look like this:

```
desc.Width = 1280;
desc.Height = 720;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;

```

---
Tags: directx11, directx9, directx10, alpha-blending
---


title: database design for browser based game

text:
# Question
Title: database design for browser based game
I'm wondering how to design a database for the player's experience, whether to create a single table that will collect basic information such as. Class, race, number of experiences, number of occupied bases, etc. Or whether it would be more ideal to divide it into individual databases

# Answer
> 0 votes
While this does not answer most of the specifics related to your game, a lot of similar questions will be answered by learning about database normalization.

It is a large topic, but it explains how to avoid all kinds of design blunders (like having a massive table with more and more fields as your object grows). For example, you have a table of players, and you want to record their inventories:

```
+-----------+-------------+--------------+--------------+------
| Player ID | Player Name | Player Level | Player Items | .....
+-----------+-------------+--------------+--------------+------
| 000000001 | Robert      | 3            | Item1, Item2 | .....
+-----------+-------------+--------------+--------------+------
| 000000002 | George      | 50           | Item3, Item1 | .....
+-----------+-------------+--------------+--------------+------

```

Like this the Items field will be requiring extra parsing and can bloat needlessly.

A first level normalization can turn this into

```
+-----------+-------------+--------------+---------------+---------------+---
| Player ID | Player Name | Player Level | Player Item 1 | Player Item 2 | ..
+-----------+-------------+--------------+---------------+---------------+---

```

but it will be still hard to maintain if you decide you want a bigger inventory.

So you go next level instead and make a separate table of item/inventory entries:

```
+----------+-----------+--------+
| Entry ID | Player ID | Item   |
+----------+-----------+--------+
| 00000001 | 000000001 | Item1  |
+----------+-----------+--------+
| 00000002 | 000000001 | Item2  |
+----------+-----------+--------+
| 00000003 | 000000002 | Item3  |
+----------+-----------+--------+
| 00000004 | 000000002 | Item1  |
+----------+-----------+--------+

```

By consulting this table you can easily see which items belong to Robert or George's character. The Entry ID column might be unnecessary if you can ensure that there are no duplicate combinations of Player ID and Item in the table - you can for example allow multiple of the same item by adding an "amount" column.

A second thing that is really useful specifically for games is called Entity-Attribute-Value system. It is used when you have a lot of different kinds of "things" that you nonetheless want to store in the same database - inventory items are again a very good example.

Why?

Here are three very common RPG style items:

Item 1:

Name: Health Potion

What it does: restore health

How much? 50

How much does it cost? 100 gold pieces.

Item 2:

Name: Magic Sword

What it does: nothing, but you can equip it.

If equipped, your character's attack is increased by 10. Also, they dodge hits better now. Also, they have a chance of setting their enemy on fire.

How much does it cost? 500 gold pieces.

Item 3:

Name: Carrot

What it does: nothing, it is a quest item.

Who wants it: the rabbit in the town of rabbits.

How much does it cost? as a quest item it is literally priceless.

Our task is to store these items in the database. Clearly, they should all be stored in the same table, that will later be referred to by our inventory table - but we cannot really store all these vastly different properties in just ONE table. It does not make sense for a sword to have store a number for how many health points it can recover if you drink it. The quest item has no price, and the potion does nothing when equipped. The sword has 3 different but similar things that happen when it is equipped. Total chaos.

What you can do then is to create a table of "things" - in this case, items - and store some bare minimum in that table. Usually, one stores an ID to identify the specific thing uniquely, and an extra field roughly specifying the "type" of a thing, perhaps some other common parameters that are often used - maybe icon ID or the "rarity" of an item - so you can draw a nice little border around the rare and legendary ones.

All the rest are in their own separate table, a kind of a key-value store:

```
+----------+---------+------------+--------+
| Entry ID | Item ID |  Attribute | Value  |
+----------+---------+------------+--------+
| 00000001 | Item1   | health_up  | 50     |
+----------+---------+------------+--------+
| 00000002 | Item2   | atk_equip  | 10     |
+----------+---------+------------+--------+
| 00000003 | Item2   | evasion_up | 10     |
+----------+---------+------------+--------+
| ........ | .....   | .........  | ....   |

```

You get the idea. Now all you have to do to "reassemble" your item from the database is to look in your attributes and retrieve all the ones that have Item ID same as the item you're working with.

---
Tags: mmo, databases, browser-based-games
---


# Question
Title: How to create a countdown timer that shows hours, minutes and seconds in unity?
Kind of an easy question but everything I have found on this topic is either outdated or only counts down numbers and not time which is what I need. How can I go about creating a countdown timer where I can input a public float or int for time and then the text on screen will count it down to zero in a time format (00:00:00).

For example if I input "120" (or whatever the proper way to input time is) for instance, then the countdown timer would format correctly to "02:00" then start counting down by seconds. The tutorials ive seen just count down by numbers and dont take time into account (120,119,118, etc)

On top of that I am confused on how to implement a way to activate scripts at a certain time, for example at "1:00" left I would like to send a warning message or something. Please help and thanks!

# Answer
## Keeping track of time

You likely already figured out that the best way to keep track of time left in Unity is to have a `private float` variable which gets initialized to the starting time and then gets reduced by Time.deltaTime in the `Update` method:

```
secondsLeft -= Time.deltaTime;

```

## Creating a UI timer

But the problem is that Unity does not provide a comfortable way to format a number of seconds in a float-variable in a human-readable format. But fortunately there is a class for that in the C# standard library: The class `TimeSpan`.

```
TimeSpan timeSpanLeft = TimeSpan.FromSeconds(secondsLeft) ;

```

Create a text element on your UI canvas and set its text like this:

```
yourUiTextElement.text = timeSpanLeft.ToString();

```

The method ToString of TimeSpan by default gets you the time left in the format `hh:mm:ss.ffffff`. If you want to omit the milliseconds, you can also pass a format string to it. If you always want it in the format hh:mm:ss, you would call it like that:

```
yourUiTextElement.text = timeSpanLeft.ToString(@"hh\:mm\:ss");

```

## Handle events when the timer reaches a certain value

A common beginner mistake is to write code like that and expect it to trigger reliable:

```
if(secondsLeft == 60.0f) { // <- WRONG!

```

`Time.deltaTime` skips ahead in unpredictable intervals, so while you can expect a value controlled by it to be larger or smaller than a constant, you can never expect it to be *exactly equal* to a constant. You must not check if there are *exactly* 60 seconds left, because it's more likely than not that the value will change from a little over `60.0` to a little under `60.0` between two updates. You can only check if there are *60 seconds or less* left. And in order to only trigger the event once and not every single update after the 60 second mark, you also need a bool variable which keeps track of whether this event has already happened or not.

```
if(secondsLeft <= 60.0f && warningDisplayed == false) {
     // display the warning message
     warningDisplayed = true;
}

```
> 2 votes

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


# Question
Title: Start Countdown on Resuming Game (Unity)
I am pausing game by setting Time.timeScale to 0. And When the Game resumes Time.timeScale is set to 1f again, and game resumes. Now I want to add timer before actually resuming game. It shows 3,2,1,Go and player starts running. But problem is that It is not counting as Time.timeScale is set to zero. And if i set Time.timeScale to 1, the player starts running immidiately and countdown also starts perallaly. Actually I want to start countdown first and then to resume game. I've added the code below, that i've used. The game and timer both is activated perallally by following code.

```
IEnumerator WaitToResumeGame()
{
    for (int i = 0; i <= 3; i++) {
        yield return new WaitForSeconds (1f);
        TimerText.GetComponent<Text> ().text = "" + i;
    }
    TimerText.SetActive (false);
}

public void ResumeGame()
{
    pausePanel.SetActive (false);
    TimerText.SetActive (true);
    Time.timeScale = 1f;
    StartCoroutine (WaitToResumeGame ());
}

```

# Answer
> 2 votes
You can use a little trick for that:

use the `Time.realtimeSinsceStartup` property

when you end the pause set a variable like

```
float endPause = Time.realtimeSinceStartup + 3; //for 3 Seconds countdown

```

and right after that:

```
while (Time.realtimeSinceStartup < endPause){
     yield return 0;
}
Time.timeScale = 1;

```

That will cause the game to wait another 3 seconds before continuing. Of course you need to modify it a little to display a countdown but that shouldn't be a problem for you.

# Answer
> 1 votes
`yield return new WaitForSeconds` is very much affected by `timeScale`. So if `timeScale` is zero, that coroutine will never continue.

Jonas' answer is correct, but I'd like to add something you may find helpful: in Unity 5, you can write a class that does the same thing as `WaitForSeconds`, but with unscaled seconds instead of scaled. This is the class I use:

```
using UnityEngine;

public class WaitForRealSeconds : CustomYieldInstruction
{
    private float m_FinishTime;

    public WaitForRealSeconds(float seconds)
    {
        m_FinishTime = seconds + Time.realtimeSinceStartup;
    }

    public override bool keepWaiting
    {
        get
        {
            return m_FinishTime > Time.realtimeSinceStartup;
        }
    }
}

```

# Answer
> 1 votes
Use WaitForSecondsRealtime on the place of WaitForSeconds. It will work.

# Answer
> 0 votes
The following code helps me to do both, Countdown and after that to resume game.

```
IEnumerator WaitToGetReady()
{
    TimerText.GetComponent<Text> ().text = "" + 3;
    yield return WaitToResumeGame ();

    TimerText.GetComponent<Text> ().text = "" + 2;
    yield return WaitToResumeGame ();

    TimerText.GetComponent<Text> ().text = "" + 1;
    yield return WaitToResumeGame ();

    Time.timeScale = 1f;

    TimerText.SetActive (false);
}

IEnumerator WaitToResumeGame()
{
    float start = Time.realtimeSinceStartup;
    while (Time.realtimeSinceStartup < start + 1f) {
        yield return 0;
    }
}

public void ResumeGame()
{
    pausePanel.SetActive (false);
    TimerText.SetActive (true);
    StartCoroutine (WaitToGetReady ());
}

```

---
Tags: unity, timer
---


# Question
Title: How to Instantiate an array of Prefabs in a chequerboard pattern
I need to instantiate an array of 2 elements that is floors of black and white color in an alternating pattern so it looks like a chess board. It is for my game that has 2D Dungeon Generation.

This is my current code:

```
public enum TileType
{
    Wall, Floor,
}

public GameObject[] floorTiles;
public GameObject[] wallTiles;
public GameObject[] outerWallTiles;

private TileType[][] tiles;
private Room[] rooms;
private Corridor[] corridors;
private GameObject boardHolder;

void InstantiateTiles()
{
    for (int i = 0; i < tiles.Length; i++)
    {
        for (int j = 0; j < tiles[i].Length; j++)
        {
            InstantiateFromArray(floorTiles, i, j);

            if (tiles[i][j] == TileType.Wall)
            {
                InstantiateFromArray(wallTiles, i, j);
            }
        }
    }
}

void InstantiateFromArray(GameObject[] prefabs, float xCoord, float yCoord)
{
    int randomIndex = Random.Range(0, prefabs.Length);
    Vector3 position = new Vector3(xCoord, yCoord, 0f);
    GameObject tileInstance = Instantiate(prefabs[randomIndex], position, Quaternion.identity) as GameObject;
    tileInstance.transform.parent = boardHolder.transform;
}

```

}

So this is how it looks right now (just random positions of floor prefabs):

And this is what I am trying to achieve (alternating):

# Answer
> 16 votes
In the decision on what tile prefab to choose, you can think of it this way:
If **(xCoord + yCoord) % 2 == 0**, then select prefab1
If **(xCoord + yCoord) % 2 != 0**, then select prefab2

This ensures the tiles form a "chess-like" board.
**Note** that you will probably want to pass xCoord and yCoord as integers instead of floats.

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


# Question
Title: conditional statement stop and run 2 coroutine unity
The scenario will look like this: IE 1 will spawn the enemy, until the player kills the enemy and has enough points, IE 1 will stop and run IE 2. IE 2 runs spawn coin after 10s IE 2 stops and IE 1 continues to run how can i get such script,sorry my bad. many thank....

# Answer
> 1 votes
You can chain execution from one `IEnumerator` to another by `yield`ing it. So we can have one master coroutine that expresses the eternal alternation between these two phases:

```
IEnumerator AlternatingSpawnLoop() {
    // Keep looping forever.
    while(true) {
        // Run the enemy spawn loop until the enemy phase is over.
        yield return EnemySpawnLoop();
        // Run the coin spawn loop until the coin phase is over.
        yield return CoinSpawnLoop();
        // Repeat.
    }
}

```

Then write an `IEnumerator` for each phase to handle its own logic:

```
public float enemySpawnInterval = 5f;
public int scoreIncrement = 100;

IEnumerator EnemySpawnLoop() {
    int scoreGoal = ScoreManager.GetLocalPlayerScore() + scoreIncrement;

    // Keep looping until we reach or exceed 100 points from the start of the wave.
    while(ScoreManager.GetLocalPlayerScore() < scoreGoal) {
        // Spawn another enemy, then wait.
        SpawnManager.SpawnEnemy();
        yield return new WaitForSeconds(enemySpawnInterval);
    }
}

public float coinSpawnInterval = 1f;
public int coinsToSpawn = 10;

IEnumerator CoinSpawnLoop() {
    // Spawn a controlled number of coins in total (helpful for balancing)
    for(int i = 0; i < coinsToSpawn; i++) {
        // Spawn a coin, then wait.
        SpawnManager.SpawnCoin();
        yield return new WaitForSeconds(coinSpawnInterval);
    }
}

```

# Answer
> 0 votes
You will have to save the coroutine when you start it if you want to stop it later on. You can do this with:

```
IEnumerator myCoroutine = StartCoroutine(firstIE);

```

So, later on you can simply do:

```
StopCoroutine(myCoroutine);

```

So what you have to do is firstly save the initial coroutine when you call it and then modify the conditional statements appropriately.

More info on StopCoroutine

---
Tags: unity
---


# Question
Title: keeping clients up to date with server state in an mmo-like game
I'm making an online RPG that could classify as an MMO, but I'm keeping the project scope very small by making the game's systems simple, and focusing mostly on what I want to learn: real-time networking.

The problem I'm facing is that that I don't want to update every player about every other player, all the time. This is a huge waste of bandwidth, and may even be impossible without a really beefy connection.

My solution is:

* Keep track of which entities are in the client's visibility range
* Send a "full entity state" packet when the client enters the world
* Send a "create entity" packet for any entity that enters the visibility range
* Send a "delete entity" packet for any entity that leaves the visibility range
* Send a "update entity" packet for any entity that updates within the visibility range

I don't like the fact that when the client moves, I have to update the list of entities it can see, because it means I still have to loop over every entity. Is there anything better? Can this solution be improved somehow? If so, could you provide further reading, or possibly even sample implementations?

# Answer
A common solution is to divide the game world into square chunks which are as large as the visibility zone of a player.

Give each chunk a list of entities which are currently in that chunk.

When something happens in a chunk (an entity enters, leaves or does something), send that event to the players who are in the same chunk or in any adjacent chunks.

Those chunks can also be used to optimize collision detection, by the way.
> 2 votes

---
Tags: networking, mmo, realtime
---


title: Unity getting Input from UI

text:
# Question
Title: Unity getting Input from UI
So I'm trying to get a script of mine to pass information to another static class being used for saving files as I've been told I wouldn't want that script to be instantiated. So I used a separate script to get input field text. However, I seem to be encountering a problem whenever I want to save the file.

I keep getting the error "Object reference not set to an instance of the object", I have made done this though. (See code below)

The class to get the name of the file

```
public class SaveInputField : MonoBehaviour
{
    public static string saveName;
    public GameObject inputField;

    public void getFileName(string saveName)
    {

        saveName = inputField.GetComponent<Text>().text;
        Debug.Log("Save file name: " + saveName);
        SaveFile.saveName = saveName;
    }
}

```

^called whenever its been edited

The static class

public static class SaveFile
{

    public static string saveName;

    public static void SaveData(Deck deck)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        string path = Application.persistentDataPath + "/" + saveName + ".dd";

        FileStream stream = new FileStream(path, FileMode.Create);
        Debug.Log("Stream Opened");
        DeckData data = new DeckData(deck);

        formatter.Serialize(stream, data);
        stream.Close();
        Debug.Log("Stream Closed");

    }
```
</code></pre>

# Answer
> 1 votes
Here you ask for a game object:

```
public GameObject inputField;

```

But what you actually use is a text component:

```
saveName = inputField.GetComponent<Text>().text;

```

This gives multiple potential points of failure: either you forget to set the `inputField` in the inspector, or you set it, but the game object you set doesn't have a `Text` component (or the `Text` component is in one of its children), or the reference had what you need, but it got unloaded/destroyed.

If what you want is a Text component, you can just ask for that in the first place.

```
public Text inputText;

...

if(inputText == null) Debug.LogError("Remember to assign your input text!");
saveName = inputText.text;

```

For starters this is more efficient, since it saves searching for the component via `GetComponent` at runtime. But it also gets us some reliability improvements too.

Now the inspector will enforce that you reference an object that actually has a text component, reducing the number of potential failure modes and opportunities for mistakes. This can still fail if you forget to wire it up entirely, or destroy/unload the object that's being referenced, but at least now you get an error message to remind you what you did wrong. ;)

# Answer
> 0 votes
In cases where you have crashes in MonoBehaviours, i find it the best way to debug them to split each line for null checks. (absolutely slower but efficient for debugging)

For your code, you are having a crash in a particular line, if you debug that exact line you will see what will be null. But due to your compactly written code this can be somewhat hard.

I would recommend to rewrite your code into something like this :

```
if( inputField == null )
return;
Input inputComponent = inputField.GetComponent<Input>();
if( inputComponent == null )
return;
string saveNameFromComponent = inputComponent.text;

```

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


title: Multiple directional lights use cases?

text:
# Question
Title: Multiple directional lights use cases?
I have been building and designing a hobby-tier game engine and I am currently working on supporting any amount of lights of any type. I checked out Unity and it supports multiple directional lights, what would that be useful for? Doesn't one directional light (without shadow map) already light the entire scene?

# Answer
> 3 votes
There are some Use Cases:

day & night cycle with separate sun and & mooon (don't forget to turn off shadowing once the sun/moon is below horizon ;) )

Or just multiple suns ;)

A different use case could be to have a ground diffuse reflection. When the sun hits the ground, it reflects some light and causes objects to be indirectly illuminated by the ground. (don't forget to turn off shadowing of the fake lighting ;) )

---
Tags: lighting
---


# Question
Title: How to keep the object rotation while using RotateAround in Unity?
I've got an object that has a comet-like sprite rotating around it. I'm using this code in `LateUpdate()` to make it rotate and keep the comet's tail at the right position:

```
transform.position = player.transform.GetChild(0).transform.position + (transform.position - player.transform.GetChild(0).transform.position).normalized * 2f;
transform.RotateAround(player.transform.GetChild(0).transform.position, Vector3.forward, 100f * Time.deltaTime);

```

It works fine until the object moves. After moving, the comet follows the object and goes back to the orbit, but its rotation gets messed.

I've got an image describing this problem:

The image on the left shows how the comet behaves at the beginning. On the right there's a sample of how the comet's position can possibly look after moving around. I want it to always look like on the left image.

Is there any way to stick the comet to the object's orbit? It can move as fast as the object, I don't need tealistic calculations of the position changing for the comet.

# Answer
> 0 votes
Ok, I managed to solve this problem. I removed all the code posted above, made a new empty object (called rotationAxis) as the main object child and put the comet into the rotationAxis object 2f units from the center. After that, I just rotate the rotationAxis object with this code in Update(): `transform.Rotate(0f, 0f, 3f, Space.Self);`. Now, it's sticked to the player and does not lose it's own rotation.

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


title: OnTriggerEnter works...sometimes

text:
# Question
Title: OnTriggerEnter works...sometimes
I was working on a small game in which you shoot projectiles towards various targets, now I decide to use *OnTriggerEnter* instead of *OnCollisionEnter* because *OnCollisionEnter* adds a slight force to the target during collision and I don't want that(***btw, if anyone knows how to fix that, it'd be great***), so I had to use *OnTriggerEnter* instead.

So the problem is that my code works just fine when the target is still or static. But when the target is in motion, sometimes the projectile works just fine as wanted(damages the target and disables itself afterwards) and other times, the projectile literally just moves through the target without causing any damage.

I say "sometimes" because this happens completely randomly.

Here's is my code:

```
public int m_DamageAmount;
public int speed;

private Rigidbody m_Rigidbody;

private void Awake()
{
    m_Rigidbody = GetComponent<Rigidbody>();
}

private void FixedUpdate()
{
    m_Rigidbody.AddForce(transform.forward * speed, ForceMode.Impulse);
}

private void OnTriggerEnter(Collider other)
{
    if (other.gameObject.layer == LayerMask.NameToLayer("Enemy"))
    {
        ObjectHolders._ImpactFX.Play();
        ObjectHolders._ImpactFX.transform.position = other.transform.position;

        EnemyBrain enemy = other.GetComponent<EnemyBrain>();
        if (enemy != null)
            enemy.Damage(m_DamageAmount);

        gameObject.SetActive(false);
    }
}

```

**Here are other things I've tried:**

1) I have changed both the target and the projectile's movements from transform to rigidbody.

2) I have tried changing my game time's *Fixed Timestep* value from *0.02* to *0.1*.

These things did not have any visual effects on it.

# Answer
This sounds like "tunneling" \- the collider is on one side of the object in one step, and the other side on the next step, and no collision happens in between.

Some solutions you can try:

* Extend the collider for the bullet backward along the bullet's path, so even if it skips past an object in a single physics step, its "tail" catches it. This one's dirt cheap, but just needs a little attention to make sure you don't shoot yourself or something behind you.
* Use a Shape Cast or Continuous Collision Detection to check a swept volume of space, rather than discrete snapshots. This is more expensive, but much more robust.
* Reduce the speed of your projectiles (or, if they're meant to be super fast, consider using a hitscan raycast/shapecast for the real hit detection, and the projectile travel can be purely visual flourish)
> 0 votes

---
Tags: unity, c#, physics, projectile-physics
---


# Question
Title: How to differentiate between object types and roles?
I have a base class `Object`, and depending on how the object must behave on the scene, I have multiple abstract "role" classes, that inherits virtually from `Object`:

* `Updatable` if the object is dynamic, and must be updated every frame;
* `Collidable` if the object can collide with others, and thus must take part on collision detection;
* `Drawable` if the object is visible and must be drawn.

So, for instance, a particle special effect animation is both a `Updatable`, because it moves, and `Drawable`, because it is visible, but is not `Collidable`. A trigger may be `Updatable`, but is definitely `Collidable`, and is not `Drawable` because it is invisible.

If objects are never removed or created, this design is easy to manage: I have three lists on my world, one for each object type, that hold pointers for all objects of that type: i.e. the `updatable_list` holds a pointer to all my `Updatable`s, etc. This is what I have so far.

Now I have to add and remove objects, and this design is biting me.

When a new object is added, I would have to use `dynamic_cast` to figure out its roles and add its pointer to the proper lists. But `dynamic_cast` is usually referred as bad design and code smell, not to mention being slow.

When an object is removed, it can potentially be part of multiple lists, so I would have to track its existence across lists, maybe by storing `std::weak_ptr` instead of raw pointers, and would have to check and potentially remove every time I use an object from such list. Other options would be linear search and remove from all lists upon removal, or use `std::unordered_set` instead of `std::list` to make it fast to search and remove. But I find these other options a bit fragile, because I risk having dangling pointers if I "forget" to remove the object from some list.

So, my question, is this a good design? How can it be improved? How is this problem of different object types usually handled in game engines?

# Answer
I would suggest two different ways of solving your problem. One close to your current implementation and another more abstract concept, but that is easier to use in the long run.

First the simple changes. If i understand it correctly, your roles are all subclasses from `object`class. Since `object`doesnt have the `onDraw`-method, you cant just add it to the drawable-list.
You could just implement a default `onDraw`-method in `object`class and every subclass can overwrite this function. This way your `drawable`-list would just be an `object`list with subclasses of `object`.

But how do you know, if your subclass is a drawable and needs to be added to the drawable-list? The easiest way to create a bitflag for every list-type you have. If you set the bit of drawable and collidable on 1, then on creating this subclass it will be added to the drawable-list and the collidable-list.
To add new instances of the classes, add an integer as ID and change the lists to maps. That way, you have a map where you can add and delete instances. This way you can even choose to remove an object from a certain list (e.g. something goes invisible, remove it from the drawable-list)

Now the more complex one. Your system is on half of the way to an Entitiy-Component-System. Instead of objects, that draw themselves and can change their state, you can give those objects container with those information.
Your object (lets call it entity) has slots for those components. Your drawable-list would now point to the drawable-component (containing the grapic information) of that entity instead of the entity itself. some goes for the collidable.
Your systems like the renderer or physics-engine would simply iterate over those lists and do their job. Some systems would need multiple of those components. like rendering the position and the graphics and the physics engine the position and the bounding volume.

Next step would be, that your entity is nothing more than an ID. It holds no data other that an integer, so why even bother. Your role-list can just be lists of those components. If Entity 431 gets removed, remove the components with the same id, or yet the entry 431 in your role lists.

If you are interested in this concept, look for Entity-Component-System or ECS. You will find plenty of resources for this.
> 1 votes

---
Tags: c++, architecture, gameobject, objects
---


# Question
Title: How to display Render Target live to HUD widget in UE4
I'm making a security camera system in Unreal Engine 4. It allows the player to 'activate' the monitor, which should display the Render Target texture or the material made from it on the HUD. However, that just doesn't work. There's just no image when I try to play it. Nothing appears on the screen. I'm using blueprints btw, not C++. And yes, I did check and make sure that it's not the part that displays the HUD that's going wrong, it's the displaying of the render target to the UI widget. To display it, i've tried using the image component in the UI widget.

Can anyone help?

# Answer
Ok... I never quite figured this out(if anyone knows, still answer) but what I did instead was I created a cube that I had display the material for the render target right in front of the player camera, and had it hide/show whenever the HUD did. It looks the same as it would if it was in the HUD, but it's just a weird way to do things.
> 0 votes

# Answer
This may be updated in the newer version, I applied the Material created with Render Target to the Image in the Brush settings of my Widget BP which Material Domain needs to be "User Interface". Then the Render Target material should be shown properly in the widget even in the viewport.
> 0 votes

---
Tags: gui, unreal-4, unreal, rendertargets, blueprints
---


# Question
Title: Why can't this event call its parent event?
It's me... Back again... with another Unreal problem...

---

I have an `Event` in my `Parent Class` called `Overridable :: PreDialogueScreenEnter`

I have overridden the same Event in a Child Class:

Yet when I attempt to call the parent event from the child class, the option is greyed out.

---

**Tl;Dr:**

Why call parent event not work \>:|

# Answer
Answered my own question within minutes of asking the damn thing.

---

**How I created this problem**

When overriding parent events in Unreal, you must right click and use the context menu to add the event you want to override.

Instead, I created a custom event and named it identically to the parent event.

This provides the *same functionality*, where the overridden event is the only one called.

**However**, it does not register within the editor as an overridden event, thus the option I required never showed up.
> 1 votes

---
Tags: unreal-4, unreal, events, inheritance
---


title: How to create a mesh in code?

text:
# Question
Title: How to create a mesh in code?
Getting my feet wet with Stride (formerly Xenko), I want to build a level editor where a user can drag the mouse to create walls at runtime.

I found documentation on how to immediate draw vertices per frame, but I want those vertices to be persistently stored for a mesh.

So I tried navigating through the API with IntelliSense, but didn't get further than this:

```
public class MeshScript : SyncScript
{
    public override void Start()
    {
        Mesh mesh = new Mesh();
        // The following is what I expected, but the properties do not exist:
        mesh.Vertices = new Vector3[] { ... };
        mesh.Indices = new ushort[] { 0, 1, 2, 0, 2, 3 };

        Model model = new Model();
        model.Meshes.Add(mesh);

        Entity.Add(new ModelComponent(model));
    }

    public override void Update() { }
}

```

Does anyone have a link or can explain to me which steps are needed to do this?

# Answer
> 3 votes
You can also make your own procedural model by inheriting from `PrimitiveProceduralModelBase`. This has several advantages:

* Write less code
* Available in Game Studio with preview and gizmo in scene editor
* Properties (including material) are editable in Game Studio
* Auto-generate tangents and bi-tangents required for advanced lighting
* Auto-generate bounding box and bounding sphere for correct shadow map bias
* Auto-generate additional texture coordinate channels
* Model space position offset
* Better upload/render performance due to correct data types

The workflow to add the model in Game Studio is then:

* Add any procedural model (Cube, Plane, etc.)
* Change the dropdown to your custom procedural model implementation

The workflow in code or script is:

* Add an instance of the script below to any entity

**EDIT:** Full sources - including model update per frame - are now available here: github.com/tebjan/StrideProceduralModel

Code of the custom model:

```
[DataContract("MyProceduralModel")]
[Display("MyModel")] // This name shows up in the procedural model dropdown list
public class MyProceduralModel : PrimitiveProceduralModelBase
{
    // A custom property that shows up in Game Studio
    /// <summary>
    /// Gets or sets the size of the model.
    /// </summary>
    public Vector3 Size { get; set; } = Vector3.One;

    protected override GeometricMeshData<VertexPositionNormalTexture> CreatePrimitiveMeshData()
    {
        // First generate the arrays for vertices and indices with the correct size
        var vertexCount = 4;
        var indexCount = 6;
        var vertices = new VertexPositionNormalTexture[vertexCount];
        var indices = new int[indexCount];

        // Create custom vertices, in this case just a quad facing in Y direction
        var normal = Vector3.UnitZ;
        vertices[0] = new VertexPositionNormalTexture(new Vector3(-0.5f, 0.5f, 0) * Size, normal, new Vector2(0, 0));
        vertices[1] = new VertexPositionNormalTexture(new Vector3(0.5f, 0.5f, 0) * Size, normal, new Vector2(1, 0));
        vertices[2] = new VertexPositionNormalTexture(new Vector3(-0.5f, -0.5f, 0) * Size, normal, new Vector2(0, 1));
        vertices[3] = new VertexPositionNormalTexture(new Vector3(0.5f, -0.5f, 0) * Size, normal, new Vector2(1, 1));

        // Create custom indices
        indices[0] = 0;
        indices[1] = 1;
        indices[2] = 2;
        indices[3] = 1;
        indices[4] = 3;
        indices[5] = 2;

        // Create the primitive object for further processing by the base class
        return new GeometricMeshData<VertexPositionNormalTexture>(vertices, indices, isLeftHanded: false) { Name = "MyModel" };
    }
}

```

Code of the script that adds the model by code:

```
public class AddMyModelScript : AsyncScript
{
    // Declared public member fields and properties will show in the game studio
    public float RotationSpeed { get; set; } = 1;

    public override async Task Execute()
    {
        // Setup the custom model
        await CreateMyModel();

        while (Game.IsRunning)
        {
            // Do stuff every new frame
            Entity.Transform.Rotation *= Quaternion.RotationY(MathUtil.DegreesToRadians(RotationSpeed));

            await Script.NextFrame();
        }
    }

    async Task CreateMyModel()
    {
        // The model classes
        var myModel = new MyProceduralModel();
        var model = new Model();
        var modelComponent = new ModelComponent(model);

        // Generate the procedual model
        myModel.Generate(Services, model);

        // Add a meterial
        var material = Content.Load<Material>("MyModel Material");
        model.Add(material);

        // Add everything to the entity
        Entity.Add(modelComponent);
    }
}

```

# Answer
> 3 votes
The documentation actually has an article for this which I found while writing the question. Basically, vertices and indices are stored in `MeshDraw` instances, which are then assigned to the `Mesh.Draw` property.

A short example demonstrates this quickly by using automatically generated mesh data:

```
MeshDraw meshDraw = GeometricPrimitive.Sphere.New(GraphicsDevice).ToMeshDraw();
Mesh mesh = new Mesh { Draw = meshDraw };

```

The other more elaborate example uses custom vertex data, which is exactly what I wanted:

```
// Create vertex buffer.
VertexPositionTexture[] vertices = new VertexPositionTexture[3];
vertices[0].Position = new Vector3(0, 0, 1);
vertices[1].Position = new Vector3(0, 1, 0);
vertices[2].Position = new Vector3(0, 1, 1);
Buffer<VertexPositionTexture> vertexBuffer = Stride.Graphics.Buffer.Vertex.New(GraphicsDevice, vertices);

// Create index buffer.
int[] indices = { 0, 2, 1 };
Buffer<int> indexBuffer = Stride.Graphics.Buffer.Index.New(GraphicsDevice, indices);

// Create the mesh with a MeshDraw instance.
Mesh mesh = new Mesh
{
    Draw = new MeshDraw
    {
        PrimitiveType = PrimitiveType.TriangleList,
        DrawCount = indices.Length,
        IndexBuffer = new IndexBufferBinding(indexBuffer, true, indices.Length),
        VertexBuffers = new[]
        {
            new VertexBufferBinding(vertexBuffer, VertexPositionTexture.Layout, vertexBuffer.ElementCount)
        },
    }
};

```

And then you'd just add these `Mesh` instances to `Model`s which you put into `ModelComponent`s:

```
// Create the model with the mesh.
Model model = new Model();
model.Meshes.Add(mesh);
Entity.Add(new ModelComponent(model));

```

# Answer
> 3 votes
I posted example #5 in the mesh-from-code docs that you found.

Since then, my LoadObjTest example has expanded to load WavefrontOBJ files at runtime. It handles the wavefront parsing (with C# code), mesh instantiation, and setting up textures (diffuse, specular, emission). The relevant code is in LoadAsset.cs. If you're looking to get a textured mesh on screen, this is simple runnable reference.

Of particular note to loading WavefrontOBJ and many external formats is the VertexSoup class. Many file formats specify faces with a position and normal per vertex. However, GPU indexed drawing allows only one index per-vertex, so each vertex must be "full configured". Meaning, if edges are sharp, and a vertex position is reused with multiple normal values, in WavefrontOBJ there is only one copy of that vertex position, but in GPU VertexBuffers that position is repeated for every different fully configured instantiation. Instantiating these "unique vertex configurations" is the job of VertexSoup. If you are generating meshes from code algorithms this may not be an issue for you.

@tebjan also suggested using `ProceduralModelBase`, which can generate tangents, which are important for normal/bump mapping. I have not been able to get the tangent generation working in my example yet, so I may try to switch to that method to see if that's fruitful.

One thing I have not (yet) done in this example is address any way of reusing a generated Model setup for multiple instantiations into the world. And by this i mean, the generated model is not placed into any asset database. The game engine manages this automatically for baked-in assets to avoid wasting CPU and GPU memory. That said, different applications may have different goals here. It might be intended to recreate a unique mesh every time a WavefrontOBJ file its imported (it might have changed externally), or it might be desired to have two different mesh instantiations (if they are somehow editable or modifiable in the game). Regardless, it's an important issue to be aware of.

---
Tags: mesh, stride
---


# Question
Title: Can you use a sprite with uneven dimensions in Unity 2D?
I'm new to game development as a whole, so forgive me if this is an idiotic question in itself, but I want to use a sprite sheet where the entire sprite sheet's dimensions are 104x144, and the dimensions of an individual "pose" of the sprite is 26x36. If I can use this sprite, and I'm asking if I can, what Pixels Per Unit would I put? Again, I have absolutely no idea how this works, and I'm probably being a *huge* idiot about this entire thing.

# Answer
> 0 votes
Leave the pixels per unit at its default value.

Just below those options is a button labeled "Sprite Editor". Click this button to open the sprite editor.

In the top left corner of the sprite editor, click the button labeled "Slice".

Select type "Grid by Cell Size".

Enter pixel size X: 26, Y:36

Click the "Slice" Button

Click "Apply" in the top right corner and close the sprite editor.

EDIT: Rereading, I realize this answer does not answer your title question. Yes, you can use rectangular (and other shaped) sprites. The pixels per unit is unrelated to sprite shapes and should either left at its default value (in most cases, but not always) or set on all sprites to a common value in a tile based game.

# Answer
> 1 votes
This looks like a question you can answer by **trying it**!

Import the sprite sheet into Unity. Observe that there are no error messages, your game still builds and runs correctly, and your computer does not catch fire.

Modern devices can handle non-power-of-two textures just fine, as long as you're not using mipmaps, which usually for pixel art sprites you won't be. Unity also has the ability to re-pack these sprites into atlas textures to work more efficiently. And the size of an individual sprite within the sprite sheet doesn't matter at all, since the polygon it's being drawn on is allowed to cover as much or as little of the texture space as you want.

As a general rule: **always try the thing first**, to verify whether there is a real problem that you need to spend time asking about. Much of the time, what you try first will be good enough to continue progressing other parts of your game.

---

Regarding Pixels per Unit, remember that this is not related to the number of pixels in the image. It's related to **how many pixels make up one logical building block** of your world.

Let's say you're making a tile-based game. The logical unit of your game is then the size of one tile - that lets you position your tiles at nice clean integer positions, and reason about things like "a dash that moves 3 tiles needs to travel a distance of 3.0 units in world space". In that case, if your tile is 16 pixels, then 16 Pixels Per Unit makes sense. If a tile is 32 pixels, 32 Pixels Per Unit makes sense. No matter what the overall dimensions of the sprite sheet are as a whole.

We haven't seen your character in the context of your world, so we cant speculate whether the full 26x36 dimensions of its pose make up the right logical unit for your world. In some games, characters are larger than the game's logical unit, overhanging the edges of the tile or their collision representation. In other games, characters are smaller than the game's logical unit, fitting inside a tile with room to spare around.

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


# Question
Title: Categorized and ordered weapon switching system
I am creating a weapon switching system for my game. The weapons have specific categories and positions. And players will select them accordingly. Note that positions can be negative too, it just works as an order for which weapons in the category. And currently, there are only 9 categories, and I don't aim to change that in the future.

I will have several functions that will handle the weapon selecting but each of them in a different way:

* Select the next weapon
* Select the previous weapon
* Select the next weapon in a certain category
* Select the specific weapon (which is the easiest one to implement)

I have my categories as a class:

```
class WeaponCategory
{
    Dictionary<int, Weapon> weapons = new Dictionary<int, Weapon>();
}

```

I am using a dictionary at the moment since that was the one I thought would be the most appropriate for what I am doing. Dictionary keys represent the positions of the weapons. I am creating 9 WeaponCategory in my other script as an array, like this:

```
WeaponCategory[] categories = new WeaponCategory[9]

```

Say, I have a Pistol which is positioned at category 1 and position -2, a Shotgun positioned at category 1 and position 3, an SMG positioned at category 2 and position 1. (SMG's position doesn't matter because, in its category, there is only itself). And image the player is currently using the weapon Pistol, so while their current category is 1, their current position is -2. So when I want to select the next weapon (function #1) it should go the Shotgun whose position is higher than the Pistol. And after that, when I am using Shotgun now; if I wanted to select the prev weapon, it should go back to the Pistol again, but instead, if I select the next weapon, it should go to the SMG whose category is higher than that. The actual thing starts from here, imagine I am currently using the SMG which is the highest positioned weapon; if I select the next weapon, it should go to the weapon whose position is the lowest in the hierarchy. Function #2 does pretty much the same thing, except the reverse.

So for function #3, it is going to be a similar one above but it will happen only in the certain category the weapon is located at. Imagine I am using the Pistol if I select the next weapon in the category it will basically go to the Shotgun, and when I am using the Shotgun, and if I do that again, it should go to Pistol.

If you are familiar, that is the same system in the game CS:GO or alike.

It'd be so cool if you guys give me some code to handle that if not, a code block would do too. Thanks a bunch.

# Answer
> 0 votes
I solved my problem using SortedLists instead of Dictionaries. SortedLists automatically compares the keys (as long as the keys are common types such as ints, floats; otherwise you'll have to create a IComparer while constructing your SortedList) and sorts itself accordingly each time a new element added.

As cycling in weapon menus, you will have to check whether an element with specific key exists in a loop. For that, you can use Keys property instead. You will no more need to check if a particular key exists in your list, but you will get the index of the key using IndexOfKey() method and do the rest getting the proper key with Keys property using the index.

---
Tags: c#
---


title: How to check if grounded with rigidbody

text:
# Question
Title: How to check if grounded with rigidbody
Does anyone have a better way to make an object with a rigidbody check for ground and then jump, right now I wrote a script where a raycast is cast downwards and it checks for distance but then I discovered that a player can still jump when close to the ground and when I decrease the distance amount on raycast then the jumping works a few times (5 or 6) and then stops working, so I had to increase the distance a bit and add a delay so the player can't jump for some time after a jump. But I think there might be a better way of doing it. So does anyone have suggestions on how can I improve my script or what other method I can use to make a character with a rigidbody to check if grounded and jump?

# Answer
> 3 votes
Here is a simplified example of how you could implement a check to see if your gameObject is grounded or not. It is not perfect, but should probably work for your situation:

```
bool Grounded;

void OnCollisionStay2D(Collision2D collider)
{
    CheckIfGrounded ();
}

void OnCollisionExit2D(Collision2D collider)
{
    Grounded = false;
}

private void CheckIfGrounded()
{
    RaycastHit2D[] hits;

    //We raycast down 1 pixel from this position to check for a collider
    Vector2 positionToCheck = transform.position;
    hits = Physics2D.RaycastAll (positionToCheck, new Vector2 (0, -1), 0.01f);

    //if a collider was hit, we are grounded
    if (hits.Length > 0) {
        Grounded = true;
    }
}

```

# Answer
> 1 votes
What worked for me is the following:

```
private int countColliders = 0;

private void OnCollisionEnter(Collision collision) {
    countColliders++;
}

private void OnCollisionExit(Collision collision) {
    countColliders--;
}

private void IsGrounded() {
    return countColliders>0;
}

```

(after setting the player layer to Player and the ground layer to Ground and setting the collision table so that only Player and Ground layers collide).

# Answer
> 0 votes
Use the following script it will work well...

```
Animator anim;
Rigidbody2D rigid;
bool facingRight = true;
bool canJump = true;
public Transform startpos, endpos;
public LayerMask groundLayer;

void Start()
{
    rigid = gameObject.GetComponent<Rigidbody2D>();
    anim = gameObject.GetComponent<Animator>();
}
void Update()
{
    float move = Input.GetAxisRaw("Horizontal");
    anim.SetFloat("speed", Mathf.Abs(move));
    rigid.velocity = new Vector2(move * 5f, rigid.velocity.y);

    RaycastHit2D hit = Physics2D.Linecast(startpos.position, endpos.position, groundLayer.value);

    if (hit.collider != null)
    {
        canJump = true;
        anim.SetBool("jump", false);
    }
    if (Input.GetKeyDown(KeyCode.Space) && canJump == true)
    {
        anim.SetBool("jump", true);
        rigid.velocity = Vector2.up * 10f;
        canJump = false;
    }

    if (facingRight && move < 0)
    {
        facingRight = false;
        transform.rotation = Quaternion.Euler(transform.rotation.x, 180, transform.rotation.z);
    }
    else if (!facingRight && move > 0)
    {
        facingRight = true;
        transform.rotation = Quaternion.Euler(transform.rotation.x, 0, transform.rotation.z);
    }

}

```

Place 'startpos' empty object on the center of the character and 'endpos' empty object on the bottom of the character.

---
Tags: unity, c#, movement, jumping, rigidbody
---


# Question
Title: 3-hit combo system plays first attack animation every time
So the new input system is out, and we're using it for our game. The next hurdle I'm trying to get over is implementing a melee combo ( E-\>-E-\>E). Not 100% sure how to get the new system to execute something like that. Right now my trigger isn't resetting. Images of the animator graph at the bottom

```
public class PlayerController : MonoBehaviour
{
    Rigidbody2D _rigidbody;
    SpriteRenderer _renderer;
    Animator _animator;
    public float fallMultiplier = 2.5f;
    public float lowJumpMultiplier = 2f;

    PlayerInputActions inputActions;
    Vector2 movementInput;
    public bool inInteractionZone;
    public int attackCount = 0;
    public float attackTimeout = 0.5f;

    bool touchingWall;
    private void Awake()
    {
        HRHEventHub.OnPlayerDeath += HRHEventHub_OnPlayerDeath;
        inputActions = new PlayerInputActions();
        inputActions.Player.Move.performed += ctx => movementInput = ctx.ReadValue<Vector2>();
        inputActions.Player.Interact.performed += InteractPressed;
    }

    private void InteractPressed(InputAction.CallbackContext obj)
    {
        //TODO add attack timeout
        //Check if we are inside a interaction zone
        if (inInteractionZone)
        {
            //TODO implement
            return;
        }
        if (attackCount == 0 && _grounded)
        {

            attackCount++;
            _animator.SetTrigger("Attack");
            //_animator.SetBool("ATK1", true);
        }
        else
        if (attackCount == 1 && _grounded)
        {
            attackCount++;
            _animator.ResetTrigger("Attack");
            _animator.SetTrigger("Attack");

        }
        else
        if (attackCount == 2 && _grounded)
        {
            attackCount = 0;
            _animator.ResetTrigger("Attack");
            _animator.SetTrigger("Attack");

        }

    }

}

```

# Answer
> 1 votes
I see you have a transition arrow from the "Any" state into "Attack 1"

That means that when you set the "Attack" trigger in the "Attack 1" animation, it's valid for the animator to consume that trigger to transition from "Attack 1" (which is a member of "Any" state) into "Attack 1" again.

Remove that transition arrow so that the animator is forced to use the "Attack 1" to "Attack 2" transition instead.

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


# Question
Title: My Camera (In Unity) Is Tilting When My Character Moves (2D)
I'm trying to use Cinemachine to follow my player and whenever the player moves left or right everything shifts. I'm not sure whats causing this. I have tried giving the camera a Rigidbody2D and locking the Z. This did not work. I have attached what I think may be the appropriate settings. If you know whats causing this please leave me a comment.

# Answer
> 1 votes
Delete your Cinemachine camera. Go to **Cinemachine \> Create 2D Camera**. Now input your settings. The issue will now be resolved. The issue was you most likely clicked any of the other choice than Create 2D Camera in the drop down.

\[This\]\[1\]https://blogs.unity3d.com/2018/07/17/cinemachine-for-2d-tips-and-tricks/ is a good resource to use if you have any other troubles.

---
Tags: unity, 2d, cinemachine
---