# Question
Title: My game is not shown in Play Market New Releases
I've published my app for like an 36 hours ago. It is possible to find it with exact search query ("Village Keeper") and it is available via the direct link.

Thing is I can't find it in "New Releases" ("New Free Games") and I can't find it by typing something like "village game" or "keeper". So I have only 3 installs by me and my friends.

Is it a bug or is a new app not guaranteed to get in "New Releases"? I tried to google it but found no answers. If so, how can indie developer get into the market with no money for an ad campaign?

P. S. I tried to contact Google Support twice and 24 hours after first email passed with no reaction.

# Answer
Don't be worried friend. Any store takes time to display your game in search queries. Second thing New Games or Apps are always featured one. And obviously getting featured is not an easy task. So it is very rare that your app/game is in that list at least at very beginning.
> 2 votes

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


# Question
Title: Is there any other way to animate 2d spritesheet without Animator Component in unity?
Is there any easy way exists that animates frames without using Animator component?

# Answer
> 0 votes
Yes, here is the basic scrip I wrote with some help of anonymous somewhere on the internet. Script contains some of his code. Well, anyone can use it. I will improve it by time.

Here is the script:

```
using UnityEngine;
using System.Collections;

public class AnimationScript : MonoBehaviour
{
    [Header("Animate Once?")]
    [Tooltip("Either animation should run once or not.")]
    // Either animation should run once or not
    public bool
        _animateOnce = false;
    [Header("Time")]
    [Tooltip("Time in seconds to change frames.")]
    // Time in seconds to change frames
    public float
        _time = 1.0f;
    [Header("Sprites")]
    [Tooltip("Animation sprites.")]
    // Animation sprites
    public Sprite[]
        _sprites;

    int frameCount = 0;
    SpriteRenderer spriteRenderer;

    void OnEnable ()
    {
        frameCount = 0;
        spriteRenderer = GetComponent<Renderer> () as SpriteRenderer;
        StartCoroutine ("Animate");
    }

    void OnDisable ()
    {
        frameCount = 0;
        StopCoroutine ("Animate");
    }

    // Use this for initialization
    void Start ()
    {
        frameCount = 0;
        spriteRenderer = GetComponent<Renderer> () as SpriteRenderer;
        StartCoroutine ("Animate");
    }

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

    }

    IEnumerator Animate ()
    {
        if (frameCount >= _sprites.Length) {
            if (_animateOnce) {
                yield break;
            } else {
                frameCount = 0;
            }
        }
        if (_sprites [frameCount] == null)
            yield break;

        spriteRenderer.sprite = _sprites [frameCount];
        frameCount++;
        yield return new WaitForSeconds (Mathf.Abs (_time));
        StartCoroutine ("Animate");
    }

    public void StopAnimation ()
    {
        StopCoroutine ("Animate");
    }
}

```

**Any suggestions are always welcome.**

---
Tags: animation, unity, spritesheet
---


# Question
Title: Why is my counter not incrementing when OnTriggerEnter is called?
I have a script that handles the destruction of game objects based on what they collide with. I am trying to count the number of objects destroyed when they collide with specific objects. However, this is not happening. Instead, the counter is getting to "1" and no longer counting. Can anyone explain why?

```
public class Destroy:MonoBehaviour{
    public GameObject asteroid_explosion;
    public GameObject ship_explosion;
    private int destroy_count = 0;

    void OnTriggerEnter(Collider other){
        if(other.tag == "Boundary"){
            return;
        }

        if(other.tag == "Bolt"){
            destroy_count = destroy_count + 1;
            Instantiate(asteroid_explosion, transform.position, transform.rotation);
            Debug.Log(destroy_count);
        }

        if(other.tag == "Player"){
            destroy_count = destroy_count + 1;
            Instantiate(ship_explosion, other.transform.position, other.transform.rotation);
        }
        Destroy(other.gameObject);
        Destroy(gameObject);
    }
}

```

# Answer
> 3 votes
Your `destroy_count` variable is class level, and after collision you are destroying the gameObject have this script attached. So every object will reach at max at 1 and then destroy :)

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


# Question
Title: Is there a way to make lowpoly characters close to looking like anime?
I have never used MakeHuman but i am trying to find a way to make lowpoly human models for a game. simple game so thats why i want lowpoly.

I want to have lowpoly but be looking like anime (Japanese Cartoons).

FYI: Im using Blender and Unity for the game. i just hope i can make anime from makehuman.

# Answer
> 2 votes
Low poly or high poly, the way to get a model to look like a cartoon is all in the *shader material.* You're looking for a Toon Shader, such as this one.

---
Tags: character, 3d-modeling, makehuman
---


# Question
Title: How do I properly light characters in a Unity scene?
I made a game prototype and want to improve some of rendering the visuals through light baking (which I'm new to). While I was mostly able to do this in my environiments, I'm having issues doing this for my characters in Unity. Previously, they came out with odd-ish dark shadows in places as they were affected by light and dull colors. After I begin light baking though and adding Light probes in areas that my characters would be extremely light, especailly on the skin areas. It doesn't look good at all.

Alternatively, without using light probes, it looks like this.

I'm genuinely confused on how to properly light these characters if I can't get a middle ground of proper lighting. Can anyone help me try to understand this and solve this problem?

# Answer
I highly recommend using HDR and tonemapping to get lighting under control. For a somewhat realistic render your lights are supposed to be set quite high. You then use tone mapping to bring all the lightning back under control. You didn't mention what platform you are targeting. If it is Desktop or Webplayer then tonemapping is the way to go.
> 1 votes

---
Tags: unity, lighting, lightmap
---


# Question
Title: Delaying certain actions/functions in libgdx using Timer?
Hello I am trying to delay a part of the processes in my game, but it happend that I use one of my variables in an inner class so I have to make it final, but by making it final I can't assign new value when I find it. All I am asking for is to explain me how to do the delay without making my variable final. Here is my code:

```
public class TomatoScript implements IActorScript {

private CompositeActor tomato;
private static final int speed = 100;
private BitmapFont bFont;
private Batch bch;
ArrayList<FruitScript> fruits;
private final int dmg = 10;
private int hp = 50;
private Rectangle bounds;
private int state = 0;
private FruitScript collidetFruit;

private boolean dead() {
    return hp <= 0;
}

private void setHp(int dmg) {
    hp = hp - dmg;
}

public TomatoScript(Batch b, BitmapFont bf, ArrayList<FruitScript> fruits) {
    this.bch = b;
    this.bFont = bf;
    this.fruits = fruits;
}

@Override
public void init(CompositeActor entity) {
    this.tomato = entity;
    tomato.setPosition(200, 129);
    bounds = new Rectangle(tomato.getX(), tomato.getY(), tomato.getWidth(), tomato.getHeight());
    bch.begin();
    bFont.draw(bch, Integer.toString(hp), tomato.getX() + 20, tomato.getY() + 95);
    bch.end();

}

@Override
public void act(float delta) {
    switch (state) {
        case 0:
            tomato.setX(tomato.getX() + speed * delta);
            bounds.setX(tomato.getX());
            bch.begin();
            bFont.draw(bch, Integer.toString(hp), tomato.getX() + 20, tomato.getY() + 95);
            bch.end();
            if (tomato.getX() >= 1090) {
                tomato.remove();
            }
            if (collisionFound()) {
                state++;
            }
            break;
        case 1:
            if (collisionAct(collidetFruit)) {
                state = 0;
            }
            break;

    }

}

private boolean collisionFound() {
    for (FruitScript f : fruits) {
        if (f.getBounds().overlaps(bounds)) {
            collidetFruit = f;
            return true;
        }

    }
    return false;

}

private boolean collisionAct(FruitScript f) {
    com.badlogic.gdx.utils.Timer.schedule(new com.badlogic.gdx.utils.Timer.Task() {
        @Override
        public void run() {
            f.setCol(true);//here it says I should make the "f" final.
            f.setHp(dmg);//here also.
            setHp(f.getDmg());
        }
    },2);

    if (f.dead()) {
        fruits.remove(f);
        return true;
    }
    if (dead()) {
        if (!f.dead()) {
            f.setCol(false);
            tomato.getScripts().remove(this);
            tomato.remove();
        }
        return false;
    }

    return false;
}

@Override
public void dispose() {
}}

```

I've tried to make it final, but it ruins everything it's supposed to stop the actors do the damage taking and then the one alive to continue, but it was doing it too fast in a blink of an eye. When you make the f final, it can't get the new item it should collide with. I hope someone can help :)

# Answer
As wrote in my comment, f should be final because the timer created with an enclosure need to be sure that f will remain the same during the run() execution.

I would try to make a class deriving com.badlogic.gdx.utils.Timer.Task (lets say you call it myTimerTask) with a creator that takes the FruitScript as parameter and override run().

When in collisionAct(), you instanciate a new MyTimerTask(f) and pass it to com.badlogic.gdx.utils.Timer.Schedule().

This way you should avoid enclosure restriction.

Hope it helps.
> 1 votes

# Answer
## Solution 1

Well, let's look at the LibGDX application lifecycle:

* `new LwgjlApplication(parametershere)`
* `create()`
* `while(true && time since last frame >= 1000000000 / fps) render()`
* `dispose()`

Now if we look at this logically then most LibGDX applications run at 60 FPS but they also run on a sort of timer. The timer system that LibGDX uses is the `Display.sync()` method from LWJGL but we can't use that as we don't want to drop FPS

If we go deeper, what does `Display.sync()` use? It uses the base `System.nanoTime()` timing system which allows for precise nanosecond reactions in your program and it's built-in to Java!

How do we use this to do our delay then? We can use a few variables and an `if` statement to do the work for us easily. An example of this is posted below:

```
public class Timer {
    public static void main(String[] args) {
        long timeOfIncident = 0, timeTillReaction = 1000000000;
        boolean condition = true, timeOfIncidentSet = false, reactionOccurred = false;

        while(!reactionOccurred) {
            if(condition && !timeOfIncidentSet) {
                timeOfIncident = System.nanoTime();
                timeOfIncidentSet = true;
            }

            if(System.nanoTime() >= timeOfIncident + timeTillReaction) {
                System.out.println("Reaction in 1 second / 1 billion nanoseconds!");
                reactionOccurred = true;
            }
        }
    }
}

```

## Solution 2

We can use the default LibGDX `Timer` class:

```
float delayInSeconds = 4;
SpriteBatch exampleBatch = new SpriteBatch();
BitmapFont font = new BitmapFont();

Timer.schedule(new Task() {
    @Override
    public void run() {
        exampleBatch.begin();
        font.draw(exampleBatch, "Draws after 4 seconds!", Gdx.graphics.getWidth() / 2,
                Gdx.graphics.getHeight() / 2);
        exampleBatch.end();
    }
}, delayInSeconds);

```

Hope this helps!
> 0 votes

---
Tags: collision-detection, libgdx
---


title: Can I use New York City in my game?

text:
# Question
Title: Can I use New York City in my game?
I want to make game more realistic, for that I need a city. So, I decided to take New York City, as it can be seen through Google Maps with Street View, 3d view and much more and will help me a lot to make realistic game.

So, my simple question is: *Can I use the whole New York City in my game and publish it commercially?*

# Answer
> 4 votes
*I am not a lawyer, and this is not a legal advice site. To get a final opinion, hire a lawyer.*

There are 2 aspects in your question:

* Can I use the City of New York without doing copyright infringement?
* Can I use Google Street View and related to build the city?

## The City of New York

The name of geographic locations cannot be trademarked, so the name of the city, the streets, the various plazas, etc. can be used. (This would really be hard for media creators to create content if every one had to go through a process to get the authorization to use a city name, wouldn't it!)

However, even if the name of the city is not copyrighted, the way you *use* it can be. For instance, stuff like "I \[heart\] NY", New York City logos and such are most likely copyrighted and you should inspect each of these items with a lawyer before knowing what if it is copyrighted or not.

> \[...\] generally speaking no city would have a right to a trademark in their own to mark their city as a good or service. That said, the city of New York likely has trademarks, for example, in a certain logo or design of the name to mark certain goods, such as brochures, advertising, etc. etc. \[...\] Source

Another important point about the use of New York City: what's in it. If you know there is a restaurant named "McDonald's" at the corner of street XX and street YY, to be able to put that restaurant name and logo in your game, you will need the authorization from the restaurant. This will be a huge task for a whole city.

## About the usage of Google supplied data

The Terms of Services are quite clear (bold characters are from me to highlight the important points in this case):

> 2 . Restrictions on Use. **Unless you have received prior written authorization** from Google (or, as applicable, from the provider of particular Content), **you must not**: (a) copy, translate, modify, or **make derivative works** of the Content or any part thereof; (b) redistribute, sublicense, rent, publish, sell, assign, lease, market, transfer, or otherwise make the Products or Content available to third parties; (c) **reverse engineer, decompile or otherwise attempt to extract the source code of the Service or any part thereof**, unless this is expressly permitted or required by applicable law;

So you can't just use what's provided by Google. You can use it as a reference for building you city by your artists, but you can't just download the data, transform it, and put it in your game. Unless you get a specific authorization from them.

## tl;dr

Without a specific authorization:

* **City of New York**: yes; but only the names of geographic locations (city, streets, public places, etc.).
* **Commercial entities with their logos**: no.
* **Google data**: no.

# Answer
> -3 votes
Well I'm not an expert in this copyrights stuff but I think you can because there are many games that use New York city as the map with minor variations. So maybe you can.

---
Tags: copyright, publishing, commercial
---


# Question
Title: XNA 2 3D Objects Depth Convergence Error
Gah! I have a scene with 2 3D objects - a plane and a sphere;

the plane sits on the xy axis with a depth if -100 and diameter of 200;

the sphere diameter is 32 and sits on the xyz = 0 position;

when rendering using indexedprimitive all appears fine. the sphere appears in front of the plane.

however as i decrease the world z component of the sphere and the sphere passes through the plane and becomes hidden it shows the front of the sphere passing through first.

as if the plane were moving down over the sphere but only displaying the parts of the sphere that should be hidden.

the most puzzling aspect is that this problem only appears as one object passes through the other. when behind it is hidden, when in front visible?

Help please :)

Edit 20/12/2015

Has been suggested I upload a sequence of pics to better illustrate my problem so... Hope these help

.

```
        GlobeTarget = new RenderTarget2D(graphicsDevice, GlobeDiameter, GlobeDiameter, false,
                          SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents);
        graphicsDevice.SetRenderTarget(GlobeTarget);
        graphicsDevice.BlendState = BlendState.Opaque;
        graphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
        graphicsDevice.DepthStencilState = new DepthStencilState
            { DepthBufferEnable = true, DepthBufferFunction = CompareFunction.Less };
        graphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1, 0);

```

# Answer
> 0 votes
All thanks to DMGregory for showing me the way.

Because I was using an Orthographic view and looking straight down at objects directly facing me with NO rotation I fell foul of a really old optical illusion. I was indeed looking at the inside of my objects but my brain didn\`t realise this so interpreted the visual info as facing out. Doh!

The camera :-

```
    Projection = Matrix.CreateOrthographic(GlobeTarget.Width, GlobeTarget.Height, -500, 1000);

```

and the solution :-

```
        graphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
        graphicsDevice.DepthStencilState = new DepthStencilState
            { DepthBufferEnable = true, DepthBufferFunction = CompareFunction.Less };
        graphicsDevice.Clear(ClearOptions.DepthBuffer, Color.Black, 1, 0);

```

I only clear the DepthBuffer and NOT the Target (The texture) as before setting the graphicsDevice here I use the SpriteBatch to Draw a texture onto the RenderTarget2D that I use to build the full image. This worked beautifully and allowed me to create the following character :D

Here are two snapshots I took using the SaveAsPng texture function :-

```
        FileStream setStream = File.Open(fileName, FileMode.Create);
        StreamWriter writer = new StreamWriter(setStream);
        textureToSave.SaveAsPng(setStream, textureToSave.Width, textureToSave.Height);
        setStream.Dispose();

```

---
Tags: c#, xna, 3d, graphic-effects
---


# Question
Title: Positioning partials of character sprite animations
I'm not entirely sure how to best explain what I'm doing. Maybe I'm going about this completely the wrong way. If any of you find that that is in fact the case, I would appreciate it if you told me how I can do this better.

I've started looking into game development about a week ago and came across a cross-platform framework called LibGDX. So I started working on a practice project which is an incremental game. I'm using the sprites supplied by a program called BannedStory. I want every part of the player's body to be customizable. That means that I'm using every sprite's animations separately.

This is a snippet of code to illustrate how I'm building the character right now.

```
float playerScreenWidth = HackerStory.WORLD_WIDTH;
    float playerScreenHeight = HackerStory.WORLD_HEIGHT;

    float playerPositionX = playerScreenWidth*0.3f;
    float playerPositionY = playerScreenHeight*0.7f;

    manager = new AssetManager();

    textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheets/body/light/walking.atlas"));

    bodyAnimation = new Animation(0.25f , textureAtlas.getRegions()); // textureAtlas.getRegions()
    bodyAnimationActor = new AnimatedImage(bodyAnimation);
    bodyAnimationActor.setPosition(playerPositionX, playerPositionY);

    float bodyWidth = bodyAnimation.getKeyFrame(0).getRegionWidth();
    float bodyHeight = bodyAnimation.getKeyFrame(0).getRegionHeight();
    float bodyX = bodyAnimationActor.getX();
    float bodyY = bodyAnimationActor.getY();

    Group body = new Group();
    body.addActor(bodyAnimationActor);

    Group head = new Group();

    textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheets/head/light/walking.atlas"));

    headAnimation = new Animation(0.25f , textureAtlas.getRegions()); // textureAtlas.getRegions()
    headAnimationActor = new AnimatedImage(headAnimation);
    headAnimationActor.setPosition(bodyX - bodyWidth * 0.05f, bodyY + bodyHeight * 0.87f);

    float headWidth = headAnimation.getKeyFrame(0).getRegionHeight();
    float headHeight = headAnimation.getKeyFrame(0).getRegionHeight();
    float headX = headAnimationActor.getX();
    float headY = headAnimationActor.getY();

    head.addActor(headAnimationActor);

    textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheets/face/male/002/walking.atlas"));

    faceAnimation = new Animation(0.25f, textureAtlas.getRegions());
    faceAnimationActor = new AnimatedImage(faceAnimation);
    faceAnimationActor.setPosition(headX+headWidth*0.25f, headY + headHeight*0.1f);

    head.addActor(faceAnimationActor);

    textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheets/hair/male/003/black/walking.atlas"));

    hairAnimation = new Animation(0.25f, textureAtlas.getRegions());
    hairAnimationActor = new AnimatedImage(hairAnimation);
    hairAnimationActor.setPosition(/*headX+headWidth*0.085f*/headX+hairAnimation.getKeyFrame(0).getRegionWidth()*0.04f, headY + headHeight*0.39f);

    head.addActor(hairAnimationActor);

    Group player = new Group();
    player.addActor(body);
    player.addActor(head);

```

As you can see, I am currently setting the X position for (for example the hair) by using its parent's X co-ordinate plus a fraction of its own width. However, this causes issues when the hair is different widths. What works for one hair sprite, won't work for another.

This is what the previous code results in: https://i.stack.imgur.com/Z4RoN.jpg

I am at a loss for where to go next. I also couldn't find anything on the subject in other questions, so again, I might be completely wrong in my approach to this.

Does anyone have any idea as to how I could solve this issue?

# Answer
> 1 votes
## Solution

Well, you could get the sprite sheet and open it up in Adobe Photoshop / Pixlr as two different layers then position the hair to fit on each of the sprite animations. Then you could remove the bottom layer with the sprites and you have a row of hair textures that can all be turned into an animation via. a custom class such as this one:

```
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.*;

public class SpriteSheet {

    //All the frames from the entity
    private TextureRegion[][] textureSheet;

    //Gets the sprite sheet for the entity and splits it into frames
    public SpriteSheet(Texture spriteSheet, int tileWidth, int tileHeight) {
        //Splits the textures into a two dimensional array
        /*
         * Dimension 1: Row
         * Dimension 2: Column
         * Example:
         * ********
         * ****0***
         * ********
         * ********
         * 0 = textureSheet[1][4] to access the second row and the fifth column
         * Some of the columns may be blank, check the sprite sheet to reference
         */
        textureSheet = TextureRegion.split(spriteSheet, tileWidth, tileHeight);
    }

    //Disposes of the textures by looping through the rows then the individual columns and disposing of all the textures
    public void dispose() {
        for(TextureRegion[] textureRow : textureSheet) for(TextureRegion texture : textureRow) texture.getTexture().dispose();
    }

    //Returns the texture at a certain row or column (starting at 1,1 being textureSheet[0][0])
    public TextureRegion getTexture(int row, int column) {
        return textureSheet[row][column];
    }

    //Returns an animation using pieces of the sprite sheet
    public Animation getAnimation(int row, int columns, float animationFPS) {
        //The array that stores the frames in the animation
        TextureRegion[] animationTextures = new TextureRegion[columns];
        //Loops through the columns in the row and add them to the array of textures
        for(int i = 0; i < columns; i++) animationTextures[i] = textureSheet[row][i];

        //Returns the animation generated using the frames from the row specified and the FPS from the parameters
        return new Animation(animationFPS, animationTextures);
    }
}

```

Or you could use the gdx-texturepacker-gui application to split them into animations which is a lot more tedious than using the `Animation` class but albeit easier. It's up to you though but you can then simply draw the animations on top of each other like so:

```
exampleBatch.begin();
exampleBatch.draw(exampleBaseAnimation.getKeyFrame(stateTime, true), x, y);
exampleBatch.draw(exampleHairAnimation.getKeyFrame(stateTime, true), x, y);
exampleBatch.end();

```

If you want to look up more about LibGDX's 2D animation framework then you can check out this wiki page which gives an in-depth example of how both methods work and about delta/state time and such (delta/state time is a decimal value that represents how many frames have passed by this second so 0.1 running at 10FPS would be 1 frame passed since 0.1 * 10 and 0.2 would be 2 frames and so on and so forth with the general equation when `n` is the number of frames passed, `d` is the decimal value of delta/state time and `s` is the frames per second: `n=d*s`).

Delta/State time is useful with animation in LibGDX as LibGDX can automatically find out which frame it needs to draw using a form of the delta/state time instance that increments every frame. To get this value, create a field to store this in and just add on the delta/state time value on each frame like so: `stateTime += Gdx.graphics.getDeltaTime()`.

Hope this helps!

---
Tags: java, libgdx, animation, sprites
---


# Question
Title: How can I have a value increase by multiples of 10 in the inspector?
I have a number that I want to be editable in the inspector. However, I want to restrict that number to be a multiple of 10. I can always just go into the code and set it to the nearest multiple of 10, but I'd rather force it in the inspector. I am willing to use an int, float, Vector, or really any sort that can hold a number. How can I do this?

# Answer
> 7 votes
I'd use `OnValidate` for this. It gets called anytime the user changes something in the Inspector, but only in the Unity editor, so it doesn't add unnecessary checks into a compiled build of the game.

```
public class SnapTest : MonoBehaviour {

    [Range(min:-50, max:50)]
    public float snappedValue;

    void OnValidate()
    {
        snappedValue = Mathf.Round(snappedValue / 10f) * 10f;
    }
}

```

This gives you a snapping slider like this:

---
Tags: unity
---


# Question
Title: Can I use hawaii state in my game commercially?
I want to make game more realistic, for that I need a state . So, I decided to take hawaii state, as it can be seen through google maps with street view, 3d view and much more and will help me a lot for making realistic game. So, my simple question is that can I use the whole hawaii state \[whole means everthing like clone/duplicate\] in my game commercially.

# Answer
> 0 votes
Wouldn't this be better for the Stackoverflow Lawyer's site? Anyway you can use the Hawaii state in your game. As long as you don't use anything from Google maps in your game. You are perfectly fine to create a level/game based around Hawaii because Google doesn't own the rights to Hawaii.

Just make sure you don't use anything from Google maps. Also, to be safe don't clone the buildings. For example don't have the same hardware store with the same name in your game that is in Hawaii. Your making profit from the hardware store.

---
Tags: game-design, graphics, copyright, graphics-design, commercial
---


# Question
Title: Unity Physics Trouble with Platform Objects
Hi Game Development Community! I'm new to designing in unity, and I'm having some issues with my player game object traveling through platform game objects. Several of my game objects (pink in pictured) are successfully acting as a surface for the ball (purple). But others (cylinders in white) are not. The ball goes straight through them. Yet I'm not seeing a difference in the cylinder and cube's physics settings I've set. Any advice or solutions to this problem are much appreciated!

# Answer
> 1 votes
Hey select the game object which is not colliding properly and check whether "isTrigger" is on , if it is then turn it off. Also make sure your collider size is covering the whole object.

# Answer
> 0 votes
The problem is with the Unity cylinder colliders. The unity cylinder collider isn't a *cylinder* but a *capsule*.

Uncheck the Mesh Renderer component of the cylinder and you will see the collider as green outline.

You need to add a mesh collider by clicking *Add Component* below.

I hope this sufficiently answers your question.

---
Tags: unity, physics, game-design
---


# Question
Title: I want to drop a platform after I land on it
I want to disable z-axis translation lock 2 seconds after my player hits the object in question. I am using Unreal 4. Been slamming my head against it for a week and a half, please save this newb.

I just noticed this is the iteration where I enabled gravity instead of disabling z lock... the intended result is be the same for both of these

UPDATE

now the thing drops but it doesnt wait for the timer

UPDATE! I DID IT!

# Answer
> 1 votes
Final solution

turns out I was using a timer and not a timeline.. timers are like stopwatches and count up, timelines are like egg timers and count down

---
Tags: unreal-4
---


title: SFML RectangleShape won't render

text:
# Question
Title: SFML RectangleShape won't render
I have a `sf::RectangleShape` in my code which is defined like this :

```
sf::RectangleShape shape_1;

```

And it's values are set like this :

```
shape_1.setFillColor(sf::Color::White);
shape_1.setPosition(10, 10);

```

But when I render it like this :

```
    window.draw(shape_1);

```

It wont display in my window.

---

My rendering part of the code looks like this :

```
    window.clear();

    window.draw(*box.getSfShape());
    window.draw(*box_static.getSfShape());
    window.draw(shape_1);

    window.display();

```

Not sure what I'm doing wrong. Have been going on for days thinking it was a position problem with a body but since this won't render either it can't be. :P

# Answer
You have to set the size of the rectangle with setSize.

```
shape_1.setSize(sf::Vector2f(100.f, 100.f));

```
> 3 votes

---
Tags: c++, rendering, sfml
---


# Question
Title: HLSL Shadowmap shader for large scale environments
I'm working on a racing game in Monogame. The game runs fine so far using Monogame's BasicEffect (link to video).

I wanted to add shadows so I implemented a shadowmap using this as a base. and a shadowmap of 4096x4096 I get nice shadows:

My game actually has a draw distance of 500 units instead of the 20 units used in my test code. This greatly reduces the accuracy of the shadowmap, so much it becomes unusable (some blobs appear under some of the cars). For example the same code with a projection distance of 200 units:

**Now to my question:** How can I improve the quality of the shadows with bigger draw distances?

I tried using different drawdistances for the shadowmap and for the actual drawing (hoping shadows would not matter in the far distance) but it produced more artefacts than decent shadows.

I'm considering scaling my entire game down- but it would mean scaling the ingame logic as well so I'm hoping to find an answer here first.

**Edit: this is the (currently not working) shader I'm working on based on János Turánszki suggestions**

```
float4x4 World;
float4x4 View;
float4x4 Projection;
float4x4 LightViewProjClose;
float4x4 LightViewProjMedium;
float4x4 LightViewProjFar;

float3 LightDirection1 = float3(-1.5, 0.45, 0);
float4 LightColor1 = float4(1, 1, 1, 1);
float3 LightDirection2 =float3(1,1,0.2);
float4 LightColor2 = float4(0.2, 0.2, 0.25, 1);

float4 AmbientColor = float4(0.15, 0.15, 0.15, 0.15);
float DepthBias = 0.001f;

texture ShadowMap;
sampler ShadowMapSampler = sampler_state
{
    Texture = <ShadowMap>;
};

struct VertexShaderInput
{
    float4 Position : SV_POSITION;
    float4 Normal : NORMAL0;
    float4 Color : COLOR0;
};

struct ShadowVertexShaderInput
{
    float4 Position : SV_POSITION;
    float4 Normal : NORMAL0;
    float4 Color : COLOR0;
};

struct VertexShaderOutput
{
    float4 Position : SV_POSITION;
    float4 Normal   : TEXCOORD0;
    float4 Color    : COLOR0;
    float4 WorldPos : TEXCOORD2;
};

struct CreateShadowMap_VSOut
{
    float4 Position : POSITION;
    float4 Color : COLOR0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4x4 WorldViewProj = mul(mul(World, View), Projection);

    // Transform the models verticies and normal
    output.Position = mul(input.Position, WorldViewProj);
    output.Normal =  input.Normal;
    output.Color = input.Color;

    // Save the vertices postion in world space
    output.WorldPos = mul(input.Position, World);

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    // Color of the model
    float4 diffuseColor = input.Color;

    // Intensity based on the direction of the light
    float diffuseIntensity1 = clamp(dot(input.Normal.xyz, LightDirection1.xyz),0,1);
    float diffuseIntensity2 = clamp(dot(input.Normal.xyz, LightDirection2.xyz), 0, 1);

    // Final diffuse color with ambient color added
    float4 diffuse = saturate((diffuseIntensity1 * LightColor1 + diffuseIntensity2 * LightColor2) * diffuseColor);

    // Find the position of this pixel in light space in the close projection
    float4 lightingPosition = mul(input.WorldPos, LightViewProjClose);

    if (((lightingPosition.x > -0.5) && (lightingPosition.x<0.5)) && ((lightingPosition.y>-0.5) && (lightingPosition.y < 0.5)))
    {
        // Find the position in the shadow map for this pixel
        float2 ShadowTexCoord = 0.5 * lightingPosition.xy /
            lightingPosition.w + float2(0.5, 0.5);
        ShadowTexCoord.y = 1.0f - ShadowTexCoord.y;

        // Get the current depth stored in the shadow map (red component for close)
        float shadowdepth = tex2D(ShadowMapSampler, ShadowTexCoord).r;

        // Calculate the current pixel depth
        // The bias is used to prevent folating point errors that occur when
        // the pixel of the occluder is being drawn
        float ourdepth = (lightingPosition.z / lightingPosition.w) - DepthBias;

        // Check to see if this pixel is in front or behind the value in the shadow map
        if (shadowdepth < ourdepth)
        {
            // Shadow the pixel by lowering the intensity
            diffuse *= float4(0.5, 0.5, 0.5, 0);

        };

    }

    lightingPosition = mul(input.WorldPos, LightViewProjMedium);

    if (((lightingPosition.x > -0.5) && (lightingPosition.x<0.5)) && ((lightingPosition.y>-0.5) && (lightingPosition.y < 0.5)))
    {
        // Find the position in the shadow map for this pixel
        float2 ShadowTexCoord = 0.5 * lightingPosition.xy /
            lightingPosition.w + float2(0.5, 0.5);
        ShadowTexCoord.y = 1.0f - ShadowTexCoord.y;

        // Get the current depth stored in the shadow map (green component for medium)
        float shadowdepth = tex2D(ShadowMapSampler, ShadowTexCoord).g;

        // Calculate the current pixel depth
        // The bias is used to prevent folating point errors that occur when
        // the pixel of the occluder is being drawn
        float ourdepth = (lightingPosition.z / lightingPosition.w) - DepthBias;

        // Check to see if this pixel is in front or behind the value in the shadow map
        if (shadowdepth < ourdepth)
        {
            // Shadow the pixel by lowering the intensity
            diffuse *= float4(0.5, 0.5, 0.5, 0);
        };
    }

    //do the same trick using the 'far' matrix.
    lightingPosition = mul(input.WorldPos, LightViewProjFar);
    if (((lightingPosition.x > -0.5) && (lightingPosition.x<0.5)) && ((lightingPosition.y>-0.5) && (lightingPosition.y < 0.5)))
    {
        // Find the position in the shadow map for this pixel
        float2 ShadowTexCoord = 0.5 * lightingPosition.xy /
            lightingPosition.w + float2(0.5, 0.5);
        ShadowTexCoord.y = 1.0f - ShadowTexCoord.y;

        // Get the current depth stored in the shadow map (blue component for far)
        float shadowdepth = tex2D(ShadowMapSampler, ShadowTexCoord).b;

        // Calculate the current pixel depth
        // The bias is used to prevent folating point errors that occur when
        // the pixel of the occluder is being drawn
        float ourdepth = (lightingPosition.z / lightingPosition.w) - DepthBias;

        // Check to see if this pixel is in front or behind the value in the shadow map
        if (shadowdepth < ourdepth)
        {
            // Shadow the pixel by lowering the intensity
            diffuse *= float4(0.5, 0.5, 0.5, 0);
        };
    }
    return diffuse;
}

CreateShadowMap_VSOut ShadowVertexShaderFunction(VertexShaderInput input)
{
    CreateShadowMap_VSOut output;

    float4 position;
    float4 color;

    //check against close projection
    float4 lightingPosition = mul(mul(input.Position, World), LightViewProjClose);
    //by calculating the pixel position- find if it is part of the close projection matrix.

    if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
    {
        position = mul(input.Position, mul(World, LightViewProjClose));
        color = float4(position.z / position.w, 0,0,0); //place in R component
    }

    //check against medium projection
    lightingPosition = mul(mul(input.Position, World), LightViewProjMedium);

    if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
    {
        position = mul(input.Position, mul(World, LightViewProjMedium));
        color = float4(0,position.z / position.w, 0, 0); //place in G component
    }

    //check against far projection
    lightingPosition = mul(mul(input.Position, World), LightViewProjFar);

    if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
    {
        position = mul(input.Position, mul(World, LightViewProjFar));
        color = float4(0, 0, position.z / position.w, 0); //place in B component
    }

    output.Position = position;
    output.Color = color;
    return output;
}

float4 ShadowPixelShaderFunction(CreateShadowMap_VSOut input) : COLOR0
{
    return input.Color;
}

technique MyTechnique
{
    pass Pass1
    {
        VertexShader = compile vs_4_0_level_9_3 VertexShaderFunction();
        PixelShader = compile ps_4_0_level_9_3 PixelShaderFunction();
    }
}

technique ShadowTechnique
{
    pass Pass1
    {
        VertexShader = compile vs_4_0_level_9_3 ShadowVertexShaderFunction();
        PixelShader = compile ps_4_0_level_9_3 ShadowPixelShaderFunction();
    }
}

```

# Answer
The standard way of handling this is by using cascaded shadow maps.

The idea is that you render multiple shadow maps. Objects closer to the camera should be rendered to a smaller shadow map near the camera, distant objects to a bigger shadow map. If the shadow maps are the same resolution, then you get fine details to shadows which are close to you because you get more shadow map pixels per world units, while farther away shadows will get much less detail, but you won't notice that because they are far from you.
The trick is how you select the cascades so it will look good.

A nice article which is more in-depth: MSDN
> 2 votes

---
Tags: xna, shaders, monogame, shadow-mapping
---


# Question
Title: Prevent cheating in html Javascript game
I have made a Javascript/html game. Now the problem I have is anyone can edit the client code and cheat in game for example there is a man shooting a enemy.

* Man HP: 100
* Enemy HP: 50

```
<div id ="man" hp="100" >
</div>

```

Now if someone changes the hp attribute to a very high value then he becomes literally immortal making the game easy. Now how can I prevent this type of thing ?

# Answer
You can't.

Javascript is executed on the users machine. Whatever is executed on the client side can be manipulated by the client. All mainstream web browsers come with powerful debugging tools out-of-the-box which allow users to influence Javascript code even more than with the console. So the user doesn't even need any special software tools like they would for cheating in games implemented as binary executables.

You could try to minify and obfuscate your code beyond recognition (there are tools for that which you can integrate into your deployment script), but a determined hacker can still find out where you are hiding the important data. So you might slow them down, but you can not stop them.

The only way to prevent cheating in a web-based game is to implement all important game mechanics on a server where it is out of reach for the user.

But keep in mind that when your game has no multiplayer component or global leaderboards, then it is questionable if any work invested in preventing cheating is really providing any benefit. Cheaters can only hurt their own game experience while the honest players who want to play the game as designed won't be affected at all. Allowing a bit of cheating can even enhance the game experience because it allows players to experience the game in a different way. There is a reason many game developers intentionally add cheat codes or developer consoles to their games.
> 59 votes

# Answer
Put spoilers for the new star Wars movie and or other movies/books/shows in the code to deter people from looking at the code.
> 17 votes

# Answer
Well, for me personally it depends fully on what type of javascript game that it is:

## In the case of a single player game...

***let them cheat!*** Lets say you rewrite the wheel, and put as many roadblocks in the way of a determined hacker as you want, at the end of the day, the player will only undermine the fun of the game for themselves if they cheat. If anything, the more in the way of trying to 'protect' your game, that much more of a challenge it is to hackers who will find your feeble attempts entertaining. In the end, players that don't want to cheat, wont. I personally would even add a console command or a cheat menu, to make double sure that there is no challenge here for hackers. Think of any single player game with a console (skyrim, fallout 3/4, etc...) --- at a certain point, it really doesn't matter if someone cheats or not. I personally would say the same thing for lan games as well (depending on the game).

## Otherwise, when it actually matters...

In games where cheating not only ruins the fun for the player, but for potentially all players (including those that don't want to cheat), then you really have absolutely no choice but to run anything of importance on a server. You most likely will be doing this already for any game that has a great deal of players in it that must all communicate with each other. Connections to the server, and communications to and from the server can/should all be logged and reviewed to make sure no funny business is going on. It is important that you never trust any communication that is directed towards your server. For the same reason as the single player game, you can do nearly nothing in the way of 'preventing cheating' on your players computer and any local security measures are little in the way of challenge; Because of this sent messages that 'look legit' can easily be far from it --- it is your job to check everything and trust nothing. If something does not match up exactly with what you would expect, log it and toss it.

## Why does javascript suck?!

Javascript is easy to screw with in a web browser. Firstly, it's all in plain text english, and most browsers these days pride themselves on showing you everything they can about what is on a web page on the nuts and bolts level. This means, with nothing more than a few mouse clicks later, boom, any javascript game can be viewed and easily changed. Whereas Javascript might be the easiest in these regards to 'figure out', there is not a programming language or environment known to man, that someone can't figure out. The problem is always the same: If a CPU is expected to know what to do with something, a human can figure it out too (even though it can be an absolute pain, to the point that most would rather give up than continue trying--- but not all do).

The same holds true for packets. Not only can the codes that run on your computer be completely broken apart and added to, but the communications coming from your computer to a server can be altered, resent, and forged altogether. For instance, if in a game, your computer sends to a game server out there 'hey, I just got 1 point', you can watch that communication and send it again and again... so instead of just having the one point that the game generated, you now have just as many as you want to request- or if you can figure out the communication and edit it yourself, you could easily send over 'hey, I just got 9999 points'.

## Things not to do

If you have a multiplayer game, DON'T just obfuscate it and call it a day, that stops absolutely nobody and most likely just as easy as it was for you to obfuscate, hackers have already written a tool to reverse it (or if not already most likely momentarily)... Not only can whatever mess you made can be cleaned up, but most of the time whatever you had can be entirely recreated like nothing ever happened (MCP comes to mind). All this could ever serve to do is slow someone down, but not for long. Again, you could obfuscate your code for a single player game, but what would even be the point of that other than to give hackers reason to release all manner of trainers to try and enable cheating --- you should just beat them to the punch and be done with it, rather than invite hackers to think too much about your game in particular.

## tl;dr

Because of limitations of programs and packets, for single player games there is absolutely nothing you can do to stop someone from cheating, so don't bother and rather embrace that fact. For multiplayer games, the only thing you can do is to treat all communications from a player as hostile until you can definitively prove otherwise.
> 10 votes

# Answer
One of the things you can do is *work with it*.

Really, this depends on what you want to do, but Orteil made Cookie Clicker. The game is clear javascript/html.

He took into account that the game was really open source and he added a "cheat" mode. The cheat mode allows you to cheat, but it also "records" it in your stats.

This is not available to *any* kind of game, but you could try and sneak it into your game and make it a feature. It's harder to do with multiplayer games, but if you make some features server computed only, and let the users "cheat" for trivial thing, this could make an interesting feature :)
> 3 votes

# Answer
Usually i would say if its singleplayer,let them cheat!

But you can do more than that.

For example: You could create a boolean that turns to true when your health is being edited (like for example being attacked) and false once its done,and additionally create a loop that checks the previous value of your health every loop and if its different and the boolean isnt set to true,youve got a cheater.

Keep in mind,this would be **bad** practice,and could be reverse engineered in seconds making it useless. But get creative!
> -2 votes

---
Tags: javascript, html, jquery, hacks
---


title: Play soundcloud in Unity 3d

text:
# Question
Title: Play soundcloud in Unity 3d
I'm trying to make a game with cool soundtracks from a bunch of artists. I've made a few playlists in Soundcloud (soundcloud.com) and am trying to get those to play inside of Unity 3d. Is it possible to do that? I can get a mp3 url from the api but then how do I play it? I'm planning to mac and windows. Please help, thanks! \<3

# Answer
I see you know how to get songs from the API, so i'll skip that part.

If your game is on mobile, you can just get the song with the WWW and use the .GetAudioClip method:

```
WWW www = new WWW (musicUrl);
while(!www.isDone){
    yield return 0;
}
GetComponent<AudioSource> ().clip = www.GetAudioClip(false, true);

```

However, if you run your game on PC (and that includes the Unity Editor), you'll get an error:

> Streaming of 'mp3' is not supported on this platform.

Apparently, mp3 isn't supported on Desktop, and since SoundCloud's API only serves mp3 files, you'll have to use an external library to decode the mp3 file.

You can download NAudio (documentation here) and follow these steps:

* In the Unity Editor, select Edit\>Project Settings\>Player and set the Api Compatibility Level (near the end) to .NET 2.0
* Add NAudio.dll to your Project's Plugins folder
* Create a new C# file with the following:

```
using UnityEngine;
using System.IO;
using System;
using NAudio;
using NAudio.Wave;

public static class NAudioPlayer {
    public static AudioClip FromMp3Data(byte[] data)
    {
        // Load the data into a stream
        MemoryStream mp3stream = new MemoryStream(data);
        // Convert the data in the stream to WAV format
        Mp3FileReader mp3audio = new Mp3FileReader(mp3stream);
        WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(mp3audio);
        // Convert to WAV data
        WAV wav = new WAV(AudioMemStream(waveStream).ToArray());
        Debug.Log(wav);
        AudioClip audioClip = AudioClip.Create("testSound", wav.SampleCount, 1,wav.Frequency, false);
        audioClip.SetData(wav.LeftChannel, 0);
        // Return the clip
        return audioClip;
    }

    private static MemoryStream AudioMemStream(WaveStream waveStream)
    {
        MemoryStream outputStream = new MemoryStream();
        using (WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
        {
            byte[] bytes = new byte[waveStream.Length];
            waveStream.Position = 0;
            waveStream.Read(bytes, 0, Convert.ToInt32(waveStream.Length));
            waveFileWriter.Write(bytes, 0, bytes.Length);
            waveFileWriter.Flush();
        }
        return outputStream;
    }
}

/* From http://answers.unity3d.com/questions/737002/wav-byte-to-audioclip.html */
public class WAV  {

    // convert two bytes to one float in the range -1 to 1
    static float bytesToFloat(byte firstByte, byte secondByte) {
        // convert two bytes to one short (little endian)
        short s = (short)((secondByte << 8) | firstByte);
        // convert to range from -1 to (just below) 1
        return s / 32768.0F;
    }

    static int bytesToInt(byte[] bytes,int offset=0){
        int value=0;
        for(int i=0;i<4;i++){
            value |= ((int)bytes[offset+i])<<(i*8);
        }
        return value;
    }
    // properties
    public float[] LeftChannel{get; internal set;}
    public float[] RightChannel{get; internal set;}
    public int ChannelCount {get;internal set;}
    public int SampleCount {get;internal set;}
    public int Frequency {get;internal set;}

    public WAV(byte[] wav){

        // Determine if mono or stereo
        ChannelCount = wav[22];     // Forget byte 23 as 99.999% of WAVs are 1 or 2 channels

        // Get the frequency
        Frequency = bytesToInt(wav,24);

        // Get past all the other sub chunks to get to the data subchunk:
        int pos = 12;   // First Subchunk ID from 12 to 16

        // Keep iterating until we find the data chunk (i.e. 64 61 74 61 ...... (i.e. 100 97 116 97 in decimal))
        while(!(wav[pos]==100 && wav[pos+1]==97 && wav[pos+2]==116 && wav[pos+3]==97)) {
            pos += 4;
            int chunkSize = wav[pos] + wav[pos + 1] * 256 + wav[pos + 2] * 65536 + wav[pos + 3] * 16777216;
            pos += 4 + chunkSize;
        }
        pos += 8;

        // Pos is now positioned to start of actual sound data.
        SampleCount = (wav.Length - pos)/2;     // 2 bytes per sample (16 bit sound mono)
        if (ChannelCount == 2) SampleCount /= 2;        // 4 bytes per sample (16 bit stereo)

        // Allocate memory (right will be null if only mono sound)
        LeftChannel = new float[SampleCount];
        if (ChannelCount == 2) RightChannel = new float[SampleCount];
        else RightChannel = null;

        // Write to double array/s:
        int i=0;
        while (pos < wav.Length) {
            LeftChannel[i] = bytesToFloat(wav[pos], wav[pos + 1]);
            pos += 2;
            if (ChannelCount == 2) {
                RightChannel[i] = bytesToFloat(wav[pos], wav[pos + 1]);
                pos += 2;
            }
            i++;
        }
    }

    public override string ToString ()
    {
        return string.Format ("[WAV: LeftChannel={0}, RightChannel={1}, ChannelCount={2}, SampleCount={3}, Frequency={4}]", LeftChannel, RightChannel, ChannelCount, SampleCount, Frequency);
    }
}

```
* Use it like this

```
WWW www = new WWW (musicUrl);
while(!www.isDone){
    yield return 0;
}
GetComponent<AudioSource> ().clip = NAudioPlayer.FromMp3Data(www.bytes);

```
> 3 votes

# Answer
I don't think you'd like that. As for today SoundCloud does not have an API for Unity or mobile platforms. I'm not sure but to include their sdk you'd first have to build a library first and experiment A LOT (SO LOT, MUCH LOT, WOW!). Secondly, SoundCloud API's Streaming Sound Docs state you must follow strict guidelines to include their player in your app (or stream it in the app).

In a word - it's tedious. It would be much simpler to create your own server with a bunch of mp3 files in there and download them on request. Advantage of this is that you can keep growing your database even after you launch your game (that's what you need right?). And as @Steven said, make sure it's legal
> 1 votes

---
Tags: unity, music
---


title: Modern Shader Book?

text:
# Question
Title: Modern Shader Book?
I'm interested in learning about Shaders: What are they, when/for what would I use them, and how to use them. (Specifically I'm interested in Water and Bloom effects, but I know close to 0 about Shaders, so I need a general introduction).

I saw a lot of books that are a couple of years old, so I don't know if they still apply. I'm targeting XNA 4.0 at the moment (which I believe means HLSL Shaders for Shader Model 4.0), but anything that generally targets DirectX 11 and OpenGL 4 is helpful I guess.

# Answer
> 7 votes
These are all still relevant (and free online). CG tutorial (cg is virtually identical to hlsl) would probably be a good starting point.

The GPU Gems books are sorta like recipe books for random effects, they assume you know what you're doing, but they're great resources once you're more comfortable with things.

CG Tutorial

EDIT: and yeah, just about any tutorials/books you can find on shaders will still be relevant, a shader written for Shader Model 1 will run with Shader Model 4, and in a lot of cases you'll want to target lower shader models, since many effects don't need the extra stuff offered by the newer models (you can make nice water and bloom effects with SM2.0, and then if dx9 is an option you can target lower end hardware).

# Answer
> 3 votes
There's also the ShaderX series of books. The first couple are free to download from the link and cover a range of topics, including water. The articles in the free books were originally targeting quite old shader versions, but the techniques should hopefully be clearly described and easily transferable.

# Answer
> 2 votes
Shader Languages doesn't differ so badly, thus it is possible to learn one language and transfer this knowledge to other languages. Personally I started with Cg. There are really good free resources by Nvidia.

Just have a look: http://developer.nvidia.com/page/cg\_main.html

After you get rid of the basics you can do some research at specific shaders. It happens that there is no "bloom shader" or "water effect shader", but there are several different techniques and models you can implement with shaders.

In my opinions, you don't need a book, if you are just intrested in some cool effects, but if you want to gain some knowledge in the field of computer graphics, I recommend to you the ShaderX oder GPU Gems series.

# Answer
> 2 votes
Since you listed OpenGL as a tag, and nobody else has linked to it yet, the OpenGL shading language (aka. orange book) is a pretty good resource. It covers the shading language, as well as plenty of use cases.

# Answer
> 2 votes
I'm pretty new to shaders myself but I've been reading the GPU Pro books by Wolfgang Engel. They've been blowing me away with how incredibly easy and powerful the techniques are. Also the content isn't discussed like most academic text either, it focuses more on implementation details and the trade offs between different techniques.

http://www.amazon.com/GPU-Pro-Advanced-Rendering-Techniques/dp/1568814720%3FSubscriptionId%3D008XA1X9NAPEJGHQX182%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D1568814720

http://www.amazon.com/GPU-Pro-2-Wolfgang-Engel/dp/1568817185%3FSubscriptionId%3D008XA1X9NAPEJGHQX182%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D1568817185

# Answer
> 2 votes
I just discovered this book by Patricio Gonzalez Vivo available on line: The Book of Shaders

I'm only a couple chapters in so I am unable to provide an in-depth review, but so far I'm finding it very clear, entertaining and practical. It starts at the very beginning and appears to end up covering more or less all the topics that I can name (as a total beginner in the world of graphics). It is, however, apparently a work in progress, and the later chapters are not available - I'll be eagerly awaiting updates.

P.S: You probably already know about it, but just in case, I highly recommend shadertoy.com as your first "practice sketchbook". I was initially learning in Processing, but I find this web app even better for the purposes of learning.

# Answer
> 1 votes
I've been looking for the very same thing and found this: http://wiki.gamedev.net/index.php/D3DBook:Book\_Cover

It's only available only, which is a shame, but as far as I have looked into it, is a good read.

---
Tags: opengl, directx, shaders, hlsl, directx11
---


# Question
Title: Use an int as a reference to a specific class
So I'm trying to make an efficient game where there is a grid system and every grid has a number that is able to identify what kind of block is located there. This lets me just have an array of numbers rather than an array of block-objects.

But now here is my problem, when I want to call a method from one of block classes, I only have a number to reference it. And I don't want to have a giant switch block to try and determine which block it is.

So in short, how can I get an specific int to reference a certain class without a massive if chain or switch block?

I believe Minecraft does something like this. All the blocks are saved in memory as a number, and then when the game wants to draw or call a method on one of the blocks, it uses the number at that location to reference to block to call the method. How does it do this?

# Answer
> 1 votes
You just need a small, constant array of block objects. Your block IDs will then be indices into this array.

Alternatively, you *could* use something like a HashMap to map IDs to blocks. This is generally slower and consumes more memory than a simple array, but it does have the advantage of not requiring your IDs to be contiguous, which might be useful in some situations.

---
Tags: java
---


# Question
Title: Introduction movie running before game starts
There are many games out there that feature a movie or cut scene to feature either in-game features or to set the mood for the player. Some examples are the intro from Tony Hawk Pro Skater 4, Fifa Street 2, Modern Warfare 3, etc. How do I integrate a movie I made to Unity so it launches right at the start, ends playing and then shows the main menu? Is it available for unity personal edition or is it only for pro users?

# Answer
The component you are looking for is the MovieTexture.

* Create a scene "intro" with a *UI-\>Canvas*.
* Add a *UI-\>Raw Image* to the canvas
* Import your video as a movie texture and attach it as texture to the image
* Enlarge the image so it fills the whole screen
* Add a script which plays the movie and then loads your main menu scene when the video is finished (or the player cancels it).
* Make this scene your start scene
> 8 votes

---
Tags: unity
---


# Question
Title: Position child on the edge of the parent circle while scaling unity3d
I have come across to some different situation. I have one circle sprite and i am rotating circle continuously while rotating i want to make circle smaller and larger.

I have one object on the edge of the circle i have made that object as child of the circle.

Now my problem is how to make this child object to stay at the edge while i scale circle sprite . I s this possible ?

Thanks.

# Answer
> 1 votes
You can use `transform.localPosition` to determine the position of the child object relative to its parent.

The normalized version of this vector, `.normalized`, can be multiplied with the parent's scale to get the desired local position.

You might want to set the scale of the parent to 1 and position the child accordingly if you don't already do so. Otherwise, when multiplying with the scale it will not be on the edge of the circle. Alternatively, you can use a multiplier.

# Answer
> 0 votes
If you have a circle sprite, that you want to rotate around a point other than its center, there is a much more effective way than this.

Just go to the circle sprite in assets, and change the pivot of the sprite to the edge you want it to be.

And that's it, you should get a rotation around that pivot, and when you scale, it'll stay the same. And don't forget to add the collider if you want it to collide, after you finish setting the pivot.

This is presumably what you want to do right?

# Answer
> 0 votes
Here are my steps for child objects. Maybe it's hard to solve this only in parent object?

1. Before scaling parent, remember my parent
2. When parent is scaled, leave/disconnect from my parent
3. When parent is finished scaling, go back and reconnect to original parent.

---
Tags: unity, rotation, scale
---


# Question
Title: How do I do selective water surface rendering?
I have a shader that renders the "texture" of a very realistic water on a tile in the 3D world using a Frame Buffer.

The problem is that, for example, I only want to render the part that isn't below the terrain, only for optimization. Does it make sense and how do I do that?

# Answer
> 2 votes
If you're drawing your terrain before the water tile, the terrain is writing to the z buffer (glDepthMask), and the water tile has depth testing enabled (glEnable(GL\_DEPTH\_TEST)) with only fragments closer to or equal to what's already in the depth buffer passing the test (glDepthFunc(GL\_LESS or GL\_LEQUAL)), *and* your water shader doesn't modify its depth output, *then* most drivers (perhaps all, but I can't recall if this is a requirement) will discard fragments that are behind what's already been rendered without having to fully process them.

If you're adding the water texture in a post-process stage, and thus the depth buffer or the depth of the surface of the water are not available to you, then you could mask out areas of the frame buffer using the stencil buffer. This could be done in a post-process stage after rendering the 3D world but before doing the water-stage, *or* you could create the stencil buffer mask as you draw the 3D world in the first place.

---
Tags: java, shaders, glsl
---


title: Render scene depth to texture via FBO?

text:
# Question
Title: Render scene depth to texture via FBO?
I'm trying to render my scene's depth via FBO and Render To Texture. I have a scene that I'm rendering to a texture, then render that texture to a fullscreen quad in a second pass using a fragment shader that adds a tiny offset to the fragments giving them a pixelated look. It all works fine.

Now what I'm trying to do is basically render the depth of that scene instead of the actual colors. So I change `GL_COLOR_ATTACHMENT0` to `GL_ DEPTH_ATTACHMENT` in `glFramebufferTexture` and `GL_DEPTH_COMPONENT` instead of `GL_RGB` in `glTexImage2D` when configuring the render texture. I run the scene and all I get is blackness!

What am I missing? Are there any other configs that I should be aware of? Any help is appreciated!

Here's my drawing code and framebuffer setup:

```
  int RenderToTexture(void)
{
    // Initialise GLFW
    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    // Open a window and create its OpenGL context
    window = glfwCreateWindow(1024, 768, "Playground", NULL, NULL);
    if (window == NULL) {
        fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // Initialize GLEW
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        return -1;
    }

    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    glfwSetCursorPos(window, 1024 / 2, 768 / 2);

    // Dark blue background
    glClearColor(0.0f, 0.0f, 0.4f, 0.0f);

    // Depth test and culling
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_CULL_FACE);

    // Required for core profile
    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    // Assets
    vector<vec3> Verticies, Normals;
    vector<vec2> UVs;
    vector<unsigned short> Indicies;
    LoadOBJFile("suzanne.obj", Verticies, UVs, Normals, Indicies, true);
    GLuint Texture = LoadDDSFile("uvmap.dds");

    // Create and compile our GLSL program from the shaders
    GLuint Program = LoadShaders("Vertex.shader", "Fragment.shader");

    // Uniforms
    GLuint TextureLocation = glGetUniformLocation(Program, "TextureSampler");
    GLuint LightPosLocation = glGetUniformLocation(Program, "LightPos");
    GLuint ModelToWorldLocation = glGetUniformLocation(Program, "ModelToWorld");
    GLuint MVPLocation = glGetUniformLocation(Program, "MVP");
    GLuint CameraPosLocation = glGetUniformLocation(Program, "CameraPos");
    GLuint LightIntensityLocation = glGetUniformLocation(Program, "LightIntensity");

    // Verticies
    GLuint VertexBufferId;
    glGenBuffers(1, &VertexBufferId);
    glBindBuffer(GL_ARRAY_BUFFER, VertexBufferId);
    glBufferData(GL_ARRAY_BUFFER, Verticies.size() * sizeof(vec3), &Verticies[0], GL_STATIC_DRAW);

    // UVs
    GLuint UVBufferId;
    glGenBuffers(1, &UVBufferId);
    glBindBuffer(GL_ARRAY_BUFFER, UVBufferId);
    glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(vec2), &UVs[0], GL_STATIC_DRAW);

    // Normals
    GLuint NormalsBufferId;
    glGenBuffers(1, &NormalsBufferId);
    glBindBuffer(GL_ARRAY_BUFFER, NormalsBufferId);
    glBufferData(GL_ARRAY_BUFFER, Normals.size() * sizeof(vec3), &Normals[0], GL_STATIC_DRAW);

    // Index/Elements buffer
    GLuint ElementIndexBufferId;
    glGenBuffers(1, &ElementIndexBufferId);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ElementIndexBufferId);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, Indicies.size() * sizeof(unsigned short), &Indicies[0], GL_STATIC_DRAW);

#if 1
    // Render to texture stuff

    // Generate a Framebuffer
    GLuint FramebufferId;
    glGenFramebuffers(1, &FramebufferId);
    glBindFramebuffer(GL_FRAMEBUFFER, FramebufferId);

    // Generate render texture
    GLuint RenderTextureId;
    glGenTextures(1, &RenderTextureId);
    glBindTexture(GL_TEXTURE_2D, RenderTextureId);
    //glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024, 768, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, 1024, 768, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    //glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, RenderTextureId, 0);
    glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, RenderTextureId, 0);

    // Generate a depth buffer
    GLuint DepthBufferId;
    glGenRenderbuffers(1, &DepthBufferId);
    glBindRenderbuffer(GL_RENDERBUFFER, DepthBufferId);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 1024, 768);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, DepthBufferId);

    // Draw buffers
    GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
    glDrawBuffers(1, DrawBuffers);

    // Are we good?
    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        return false;

    // Generate a quad to fill the screen with and draw our texture on
    GLfloat Quad[] =
    {
        -1.0f, -1.0f, 0.0f,
         1.0f, -1.0f, 0.0f,
        -1.0f,  1.0f, 0.0f,
        -1.0f,  1.0f, 0.0f,
         1.0f, -1.0f, 0.0f,
         1.0f,  1.0f, 0.0f,
    };
    GLuint QuadId;
    glGenBuffers(1, &QuadId);
    glBindBuffer(GL_ARRAY_BUFFER, QuadId);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Quad), Quad, GL_STATIC_DRAW);

    // Create and compile render texture shaders
    GLuint RenderProgram = LoadShaders("Passthrough.vert", "Render.frag");
    GLuint RenderTextureLocation = glGetUniformLocation(RenderProgram, "RenderTexture");
    GLuint RenderTimeLocation = glGetUniformLocation(RenderProgram, "Time");

    // -- end of RenderTexture --
#endif

    // The idea is that we render our scene normally to our render texture (via framebuffer)
    // Then render that texture to the screen (via releasing our previously bound framebuffer)
    do
    {
        // Render scene to framebuffer / render texture

        glBindFramebuffer(GL_FRAMEBUFFER, FramebufferId);
        //glBindFramebuffer(GL_FRAMEBUFFER, 0);

        glViewport(0, 0, 1024, 768);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glUseProgram(Program);

        vec3 LightPos = vec3(0, 0, 0);
        float LightIntensity = 1.0f;

        glUniform3fv(CameraPosLocation, 1, &CameraPosition[0]);
        glUniform1f(LightIntensityLocation, LightIntensity);
        glUniform3fv(LightPosLocation, 1, &LightPos[0]);

        ComputeMatricesFromInputs();
        mat4 Rotation, Translation, ModelMatrix, MVP;
        Translation = translate(mat4(), vec3(0.0f, 0.0f, -5.0f));
        Rotation = rotate(Translation, 0.0f, vec3(0.0f, 1.0f, 0.0f));
        ModelMatrix = Rotation;
        MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;
        glUniformMatrix4fv(ModelToWorldLocation, 1, GL_FALSE, &ModelMatrix[0][0]);
        glUniformMatrix4fv(MVPLocation, 1, GL_FALSE, &MVP[0][0]);
        glDrawElements(GL_TRIANGLES, Indicies.size(), GL_UNSIGNED_SHORT, 0);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, Texture);
        glUniform1i(TextureLocation, 0);

        // location = 0 : vertices
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, VertexBufferId);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

        // location = 1 : UVs
        glEnableVertexAttribArray(1);
        glBindBuffer(GL_ARRAY_BUFFER, UVBufferId);
        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);

        // location = 2 : normals
        glEnableVertexAttribArray(2);
        glBindBuffer(GL_ARRAY_BUFFER, NormalsBufferId);
        glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ElementIndexBufferId);
        glDrawElements(GL_TRIANGLES, Indicies.size(), GL_UNSIGNED_SHORT, 0);

        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
        glDisableVertexAttribArray(2);

#if 1
        // Render our texture/framebuffer to screen
        glBindFramebuffer(GL_FRAMEBUFFER, 0); // to indicate that we're not drawing to a framebuffer anymore!
        glViewport(0, 0, 1024, 768);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glUseProgram(RenderProgram);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, RenderTextureId);

        // pass the render texture to our shader (has to be loaded first - slot 0 in this case)
        glUniform1i(RenderTextureLocation, 0);
        glUniform1f(RenderTimeLocation, (float)(glfwGetTime() * 10.0f));

        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, QuadId);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

        glDrawArrays(GL_TRIANGLES, 0, 6);

        glDisableVertexAttribArray(0);
        // -- end of render to target --
#endif

        // Swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();

    } // Check if the ESC key was pressed or the window was closed
    while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
        glfwWindowShouldClose(window) == 0);

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}

```

Here's the shaders for that second/render texture pass:

Vertex shader:

```
#version 330 core
layout(location = 0) in vec3 VertexPos;
out vec2 UV;

void main()
{
    // Since we're drawing a quad (two triangles) to fill the entire screen
    // We do not need MVP because the actual quad is in projected space
    // Since UV coordinates ranges [0, 1] and our screen coordinate [-1, 1]
    // We need to map [-1, 1] to [0, 1]
    // This is done by adding vec2(1, 1) and dividing by 2
    // Now we can get the UV coordinate from the vertex position

    gl_Position =  vec4(VertexPos, 1);
    UV = (VertexPos.xy + vec2(1, 1)) / 2.0;
}

```

Fragment shader:

```
#version 330 core
in vec2 UV;
out vec3 FinalColor;

uniform sampler2D RenderTexture;
uniform float Time;

void main()
{
    FinalColor = texture(RenderTexture, UV +
            0.005 * vec2(sin(Time + 1024.0 * UV.x),
                         cos(Time + 768.0  * UV.y))).xyz;
}

```

# Answer
> 2 votes
I think the line :

```
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, DepthBufferId);

```

Is the cause of your problem. It means that you are replacing the previously GL\_DEPTH\_ATTACHMENT bound texture by a classic render buffer.

The texture is then empty when you try to render it on screen.

---
Tags: opengl, depth-buffer, frame-buffer, rendertargets, rendertexture
---


# Question
Title: Trouble in 3DS MAX 2016 exported ogre.mesh file refering the correct .material
Actually we have some trouble in exporting ogre mesh + material files correctly from 3dsmax. We are using "Easy Ogre Exporter V 2.40" for the export to ogre format. And actually just testing its features by displaying the images in Cegui-Meshviewer (http://www.ogre3d.org/tikiwiki/tiki-index.php?page=CEGUI+Mesh+Viewer).

The problem is, the mesh itself refers to a material file, which has added "default" on to it. So for example if we exported "stone.mesh" the exported material would be "stone.material" which is fine. But when inspecting the mesh inside any mesh viewing tool run on ogreengine, the mesh itself is related to a so called "stoneDefault.material" which if I want to get its attributes listed just has no attributes set. But when I inspect the material itself ("stone.material") In those mesh viewers, I can see the correct UV map related to the material and the other attributes fit to what is expected aswell. But the mesh it self seems to be using an non existing "stoneDefault.material" (thats at least the name related to it) And I also checked if it changes anythign when I just change the name of "stone.material" to "stoneDefault.material" But this jsut resaulted in 2 different materials with the same name isnide the viewer.

So my Question is: Is this probably a bug in the viiewers/exporter? Or am I missing/missunderstanding soemthing?

we selected for testing portability ogre version 1 as exporting file format.

# Answer
> 0 votes
The export and Mesh were fine. It just figured out to be a bug in the meshviewer so we had to switch the tool we used. Now everything is working fine.

---
Tags: ogre, 3dsmax, mesh, materials
---


# Question
Title: Flash animation or Sprite sheet animation good for Unity mobile games
I would like to develop dress-up and cooking kind of games. So it needs lots of animations. Our designers done the animations in the lash. I found the plugins callued GAF and UniSWF to convert flash animation to Unity or We can convert animations into sprite-sheets and animate them in Unity, But i don't know which one is the best way to do animations for mobiles with better performance and lower game size.

Any kind of suggestion is good. Thank you!

# Answer
Here are some tips:

* Try to minimize sprite sizes.
* Try to minimize number of sprites.
* Keep Spritesheet size to less than 8192x8192, as Unity does not support larger than that.

Keep tracking smooth animations as you can get in minimum number and size of frames.
> 1 votes

---
Tags: unity, animation, performance, flash
---


# Question
Title: How to stop jumping again when character is in air (double jump)?
I'm using touch inputs in my game to control the character. I would like to know how to disable my character from jumping again in the air.

```
if (FingerTouchy.phase == TouchPhase.Ended)
                {
       charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);
       float jumpForce = 250;
                        charcter.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));

                    }

```

**Update**

Im using Collision Detection

```
void OnCollisionEnter (Collision col)
    {
        if(col.gameObject.tag == "Ground")
        {
            grounded = true;

        }
    }

```

And checking if charcter is grounded

```
if(FingerTouchy.phase == TouchPhase.Ended)
            {

                    float jumpForce=250;
                    if (grounded)
                        continue;
                    charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);
                    charcter.GetComponent<Rigidbody2D>().AddForce(new Vector2(0,jumpForce));
                        grounded=false;

                }

```

using collision/collision2d doesn't work too.

# Answer
> 3 votes
I've handling ground status with raycast.

I declare a global grounded variable and use it to check if my character can jump.

In the fixed update of my character controller, i call my groundedUpdater().

```
void GroundedUpdater ()
{
    grounded = false; //Set to false every frame by default
    RaycastHit2D[] hit;
    hit = Physics2D.RaycastAll (transform.position, Vector2.down, 0.6f);
    // you can increase RaycastLength and adjust direction for your case
    foreach (var hited  in hit) {
        if (hited.collider.gameObject == gameObject) //Ignore my character
            continue;
        // Don't forget to add tag to your ground
        if (hited.collider.gameObject.tag == "Ground") { //Change it to match ground tag
            grounded = true;
        }
    }
}

```

And where i handle inputs i do this

```
if (Input.GetKeyDown (KeyCode.UpArrow)) {
        if (grounded) { // can jump
            rig.AddForce (Vector3.up * jumpPower, ForceMode2D.Impulse);
            grounded = false; //Avoid direct double jump
        }
    }

```

# Answer
> 0 votes
To do that, make a script name `Ground`. Attach `Rigidbody2D` to Ground and mark it as `Kinematic`. Assuming that your `character` has `"Player"` tag. Now time to use some `delegate` stuff.

A simple definition of `delegate` that `delegate` is use to notify other `class` on an event, even if that other `class` don't have any instance of first `class`. In other words, `delegate` does broadcast a message, then all other classes whichever wants to receive that broadcast, just set a listener in it.

For example, `class A` has an specific event. `class B` and `class C` wants to get notify when that specific even occurs in `class A` without having an instance of `class A`.

So similarly you can use `delegate` keeping a good structure of code.

```
using UnityEngine;
using System.Collections;

public class Ground : MonoBehaviour
{
    public delegate void OnCharacterLandedDelegate();
    public static event OnCharacterLandedDelegate OnCharacterLandedListener;
    // Use this for initialization
    void Start ()
    {

    }

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

    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Player")
        {
            if (OnCharacterLandedListener != null)
                OnCharacterLandedListener();
        }
    }
}

```

Now in the script where you are handling touch. Add these lines of code.

```
bool _shouldJump = true;
void OnEnable()
{
    Ground.OnCharacterLandedListener += EnableJump;
}

void OnDisable()
{
    Ground.OnCharacterLandedListener -= EnableJump;
}

void EnableJump()
{
    _shouldJump = true;
}

```

Somewhere in your code,

```
if(FingerTouchy.phase == TouchPhase.Ended)
{
    //charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);
    Jump();
}

void Jump()
{
    if (!_shouldJump)
        return;
    _shouldJump = false;
    float jumpForce=250;
    charcter.GetComponent<Rigidbody2D>().AddForce(new Vector2(0,jumpForce));
}

```

# Answer
> 0 votes
Checking the game object's velocity in y axis.

```
if (FingerTouchy.phase == TouchPhase.Ended && charcter.GetComponent<Rigidbody2D>().velocity.y==0)
                {
       charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);
       float jumpForce = 250;
    charcter.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));

                    }

```

This just works fine.

Let me know if this has any drawbacks.

# Answer
> 0 votes
```
if (FingerTouchy.phase == TouchPhase.Ended)
    {
        float jumpForce = 250;
        if (playerIsGrounded)
            charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);
            charcter.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));

    }

```

**In the grounded check code :**

```
void OnTriggerEnter(coll Collider)
{
    if (coll.tag == "Ground")
        playerIsGrounded = true;
}

void OnTriggerLeave(coll Collider)
{
    if(coll.tag == "Ground")
        playerIsGrounded = false;
}

```

---

Haven't used unity in a while but I think it's something like this?

# Answer
> -1 votes
The easiest way is to use the Boolean variable. Make it true if the character on the ground else make it false. If it is true then only add the force to the character.

Ex:

First check the player is on the ground.

This code snippet goes on ground GameObject.

```
void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Player")
        {
            if (OnCharacterLandedListener != null)
                OnCharacterLandedListener();
               new PlayerScript().canJump=true;// if player on the ground
        }
    }

```

Your input action

This code snippet goes to the Player gameobject.

```
   [HideInspector]   //Don't show  this field in the inspector.
    public bool canJump=false;

        if(FingerTouchy.phase == TouchPhase.Ended)
        {
            //charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);
            if(canJump)
                Jump();
        }

        void Jump()
        {
            if (!_shouldJump)
                return;
             _shouldJump = false;
             float jumpForce=250;
             charcter.GetComponent<Rigidbody2D>().AddForce(new Vector2(0,jumpForce));
             canJump=false; // if not on the ground
        }

```

# Answer
> -2 votes
Since I mis understood, I would use a part of @HamzaHasan 's answer, but I would not use AddForce.

I advice to not use Addforce to let a character jump/move because this is not ment for character movement, this is more or less used for explosion that give a "force" to your body, or space ships floating movement. I would advice using `transform.Translate(Vector3.up * speed * Time.deltaTime, Space.World);`. Where vector.3 defines the direction this could be;

* `Vector3.left`
* `Vector3.right`
* `Vector3.up`
* `Vector3.down`

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


# Question
Title: Sprite can jump up through platform onto platform, once while it's on platform, but falls through second time
Sorry, I'm kind of new to this whole thing and trying to learn both Unity and its use of C#. I have overlapping box colliders set up and a trigger on the lower one to allow me to jump through the lower platform. That works fine, and once on the platform, I can jump through it and land on the top, and I can make a singular jump while I am on the platform, but as soon as I jump a second time, I fall right through. Does anyone have any suggestions as to how to go about fixing this? I originally thought it was that the overlap on the two colliders was too much, or that the radius of my ground points were too large, but fixing both of those didn't do me any good. Thanks for the help!

# Answer
If you are developing in 2D environment then try to implement `Platform Effector`. In you Platform Sprite, attach a `BoxCollider2D` and mark check on `Used By Effector` and attach `Platform Effector 2D` like this, you are all done.
> 1 votes

---
Tags: jumping, platform
---


title: Xna: Texture2D from a png file

text:
# Question
Title: Xna: Texture2D from a png file
I'm making a tile based game, and I'm working for support of tilesets. I'm trying to make it so that a Texture2D is set as a chosen PNG file. I can do this with no problem f I load the image into the content pipeline, but the level editor will be used by people without access to the content pipeline. How do I go about doing this?

# Answer
You can call the Texture2D.FromStream static method. Just pass it a stream to the png file. I'm pretty sure it works without the content pipeline.
> 4 votes

# Answer
A bit late for Raj but for anyone else...

```
        string PictureLocation = @"D:\PictureName.png";
        Texture2D Newtexture =  LoadPicture(PictureLocation);

        string PictureDestination = @"D:\NewPictureName.png";
        SavePicture(PictureDestination, Newtexture);

    public static Texture2D LoadPicture(string Filename)
    {
        FileStream setStream = File.Open(Filename, FileMode.Open);
        Texture2D NewTexture = Texture2D.FromStream(graphicsDevice, setStream);
        setStream.Dispose();
        return NewTexture;
    }

    public static void SavePicture(string Filename, Texture2D TextureToSave)
    {
        FileStream setStream = File.Open(Filename, FileMode.Create);
        StreamWriter writer = new StreamWriter(setStream);
        TextureToSave.SaveAsPng(setStream, TextureToSave.Width, TextureToSave.Height);
        setStream.Dispose();
    }

```

Reading in and saving in a new location for PNG and JPEG (I think they are the only supported, but that should be good enough :).

Hope this helps anybody else with a similar problem. Stoort.
> 4 votes

---
Tags: xna, game-design, textures, tiles, map-editor
---


title: collsion detection

text:
# Question
Title: collsion detection
I am making a 2D bubble shooter game but m stuck on a point. I have printed those balls in a 2D space using 2D arrays. Each row has 3 inputs one is x coordinate,one is y coordinate and one is the color. The problem is when I shoot the ball it goes passing the other rows of the balls. I want that Ball to stop at the very first row of balls but it ain't doing so. I want to detect the collision of the shooter ball with the first row it face while moving and want to stop that ball the moment it collides...

Can someone get me out of this problem??.....

# Answer
Fortunately, determining collisions with circles can be rather easy. For the sake of this example, I'm assuming your "bubbles" are perfect circles, and not oblong ellipses.

For each step of your game, you need to update the position of your fired bubble, then you need to go through your list of bubbles already on the board, determining if the fired bubble's distance to any of these is less than the radius of a bubble times two. If the fired bubble is closer than (bubbleRadius * 2) then it must be colliding with that bubble.
> 1 votes

---
Tags: collision-detection
---


title: Help with Javascript touch button

text:
# Question
Title: Help with Javascript touch button
I tried many buttons but I can't connect them with the (Java)Script.

So I made 2 gui buttons: one for jump which was easy because I have an `if` statement and if it's `true` then jump.

But I have problems with the crouch button. Bellow is my script but I can't figure out how I can do this from Update in function Gui.

(Or if you know how to connect buttons with JS functions, please tell me: it's always a better option :D )

This is my script:

```
#pragma strict
private var tr: Transform;
private var dist: float; // distance to ground

function Start(){
   tr = transform;
   var ch:CharacterController = GetComponent(CharacterController);
   dist = ch.height/2; // calculate distance to ground
}

function Update()
{
  var vScale = 1.0;
  if (Input.GetKey("s")){
     vScale = 0.5;
  }

  var ultScale = tr.localScale.y;
  tr.localScale.y = Mathf.Lerp(tr.localScale.y, vScale, 5*Time.deltaTime);
  tr.position.y += dist * (tr.localScale.y-ultScale);
}

function OnGUI ()
{
  if(GUI.Button(new Rect(15, 330, 200, 100), "Shrink"))
  {
  }
}

```

# Answer
Not sure if this is what you are asking or not, but this is a shot in the dark.

```
 #pragma strict
 private var tr: Transform;
 private var dist: float; // distance to ground

function Start(){
   tr = transform;
   var ch:CharacterController = GetComponent(CharacterController);
   dist = ch.height/2; // calculate distance to ground
}

function Update()
{
  var vScale = 1.0;
  if (Input.GetKey("s")){
     vScale = 0.5;
  }

```

/\*I ADDED THIS BIT\**************

```
  //What this does is checks each time Update() is called if the 'c' key was hit.
  //If you are pressing the crouch key, then run the crouch function.
  if(Input.GetKeyUp("c")){
     crouch();
  }

```

/\*END OF EDIT\******************

```
  var ultScale = tr.localScale.y;
  tr.localScale.y = Mathf.Lerp(tr.localScale.y, vScale, 5*Time.deltaTime);
  tr.position.y += dist * (tr.localScale.y-ultScale);
}

function OnGUI ()
{
  if(GUI.Button(new Rect(15, 330, 200, 100), "Shrink"))
  {

```

/\* I ADDED THIS BIT\*******************************

```
        //When you press a button the player crouches.
        crouch();

```

/\*END OF EDIT\*************************************

```
  }
}

```

/\*I ADDED THIS BIT\************************

```
//This is the function that is run when you either press 'C' or press a gui button.

function crouch(){
    //make character crouch here
    //this is run once when the "Shrink Button" is pressed.
    //this is also done once when the c button is pressed.
    //Right not this only logs that the player is crouching. Additional logic will be needed for your character to actually crouch.
    Debug.Log("Crouch Button Pressed!");
}

```

/\*END OF EDIT\*****************************
> 1 votes

# Answer
Try doing this (including only the neccessary changes, not the whole script)

```
private var crouchTime:float = 0;
private var vScale:float = 1.0f;
private var prevScale:float = 1.0f;

function Update() {
    //if this frame the key down state was initiated (true once)
    if (Input.GetKeyDown("s")){
        crouchTime = 0.0f;
        vScale = 0.5f;
        prevScale = tr.localScale.y;
    }
    //if this frame the key up state was initiated (true once)
    if (Input.GetKeyUp("s")){
        crouchTime = 0.0f;
        vScale = 1.0f;
        prevScale = tr.localScale.y;
    }
    //we only need to increment up to 1
    if(crouchTime < 1) {
        crouchTime += 5 * Time.deltaTime;
    }

    var ultScale = tr.localScale.y;
    tr.localScale.y = Mathf.Lerp(prevScale, vScale, crouchTime);
    tr.position.y += dist * (tr.localScale.y-ultScale);
}

```

This creates a steady, linear transition from "crouched" to "not crouched" over the course of 0.2 seconds, as we save the starting position and the ending position as separate values, as well as how long the button has been held down (or released).

In order to prevent un-crouching while underneath an object that should keep the character crouched, you would need a separate input, eg.:

```
if (Input.GetKeyUp("s") && !mustRemainCrouched()){ }

```

Where `mustRemainCrouched()` is a method that checks to see if there is room to stand up (`Physics.CapsuleCast()` will come in handy writing this function). Be aware that this sample check is still incomplete, as if the player releases 's' and then moves into the open, they will not stand up as the key was not released that frame. From this, however, you should have all the information you need to construct your own check that will do what you need.
> 0 votes

---
Tags: unity, javascript, touch
---


# Question
Title: How to use default framebuffer's depth/stencil when rendering to a texture?
Is it possible to use the default framebuffer depth buffer when rendering to a texture (instead of using a depth texture)?

The Idea is to continue to render part of the scene normally but on a separate texture so I can later apply a post-processing effect without having to incur the cost of having another stencil/depth buffer. Ho can I do that?

# Answer
I'm sorry but you can't...

By the way, an additional depth buffer is not a resource killer. What would be costly is to re-render objects depth in the second depth buffer.

Another idea, not so resource angry would be to share the same depth buffer between two different frame buffers and render one of these frame buffers color attachment on screen at the end of the process.
> 1 votes

---
Tags: opengl, depth-buffer, frame-buffer
---


# Question
Title: How to store renderer vertex / index data in scene graph objects?
I have a `SceneNode` class which contains a `Mesh` instance. The `Mesh` class stores client side information such as vertex and index arrays (before they're uploaded to the GPU). I also have an abstracted `Renderer` class, for GL and D3D, which render the `SceneNode`s. However, I'm not sure where I should store the API specific variables, e.g. `GLuint` via `glGenBuffers` for GL, and an `ID3D11Buffer` for D3D.

The few options I've considered are:

1. Create a derived `Mesh` class for each API, e.g. `GLMesh` / `D3DMesh`
2. Create a derived `MeshData` class for each API, which is stored in the main `Mesh` class
3. Store a map of `Mesh` to API variables in each renderer, e.g. perform a lookup of `Mesh` to `GLuint` / `ID3D11Buffer` for each object that is rendered (variables would have to be generated after the scene had been updated, but before rendering).
4. Separate the logic of rendering from scenes, by visiting the `SceneGraph` after update, and generating a `RenderGraph` of all renderable nodes in the scene.

What's the recommended way of doing this?

# Answer
In my experience, the right place to make the API break is on the model data, augmented by providing some cross-API methods to generate dynamic vertex content.

I would create a MeshData class - but I wouldn't use virtual methods. As you have indicated, your can only have one API active at a time through compilation. I would simply put a MeshData class in your DirectX class and a MeshData class in your OpenGL class. Client code can hang onto a MeshData instance and access API-specific operations *when you need them* without arduous forwarding of functions via base classes, or casting. Selection of which header/cpp to include will be done via your makefile and a preprocessor macro - including global/MeshData.h will either include dx/MeshData.h or ogl/MeshData.h - but the #ifdef is then limited to writing it once in the MeshData header.

As for performing the rendering, as you have indicated you can either visit the whole scene (if you need to worry about concatenation every frame) or deposit instances of each Mesh in a list from your update. If *every* object truly needs updating, then I would simply call a function 'QueueForRendering( MeshData \*data,params... ) during the update. But that may include a lot of redundant updates on nodes that don't need it. SceneGraph issues are a different topic really, but I would be inclined to keep my list of active 'models' somewhere else so the renderer only has to traverse those models, and it can be written in an API-specific way if there are considerations there (shared VB, material batching, etc).
> 2 votes

---
Tags: opengl, architecture, directx, design-patterns
---