# Question
Title: LibGDX Android Application only running once
I'm having trouble trying to figure out why my LibGDX game only runs successfully once on Android.

Assuming the game has not been installed on the device, when I run the application from eclipse the game runs fine. After closing the game, and attempting to run the game again by opening the game on my phone (Not through eclipse) it seems to just hang on this screen forever: https://i.stack.imgur.com/QcLCW.png

From my testing, I have discovered that none of my Android Launcher code is executed, `.onCreate()` is never called. The LogCat shows that no errors are thrown and the application only seems to load the LibGDX library and then nothing. This is the entire LogCat output:

Sometimes clearing the cache and data for the game on my device seems to temporarily fix the problem, but not always.

This is the AndroidLauncher class:

```
package com.ifs_studios.cheekychameleon.android;

import java.util.HashMap;

import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Logger.LogLevel;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.games.Games;
import com.google.android.gms.plus.Plus;
import com.ifs_studios.cheekychameleon.ActionResolver;
import com.ifs_studios.cheekychameleon.CheekyChameleon;

/**
 * MemoryBlox Android Launcher.
 *
 * @author BleedObsidian (Jesse Prescott)
 */
public class AndroidLauncher extends AndroidApplication implements ActionResolver, ConnectionCallbacks, OnConnectionFailedListener {
    /**
     * Banner Advert AdMob key.
     */
    private static final String BANNER_ADMOB_UNIT_ID= "REMOVED-STACKOVERFLOW";

    /**
     * Fullscreen Advert AdMob key.
     */
    private static final String FULLSCREEN_ADMOB_UNIT_ID= "REMOVED-STACKOVERFLOW";

    /**
     * Google API Client.
     */
    private GoogleApiClient googleApiClient;

    /**
     * If currently resolving a sign in error.
     */
    private boolean isResolvingSignInError;

    /**
     * Global Leaderboard ID.
     */
    private static final String LEADERBOARD_ID = "REMOVED-STACKOVERFLOW";

    /**
     * Unique request resolve error ID.
     */
    private static final int REQUEST_RESOLVE_ERROR = 1267;

    /**
     * Unique request for achievements ID.
     */
    private static final int REQUEST_ACHIEVEMENTS = 1268;

    /**
     * Unique request for leaderboards ID.
     */
    private static final int REQUEST_LEADERBOARD = 1269;

    /**
     * Google Analytics Trackers.
     */
    private HashMap<TrackerName, Tracker> trackers = new HashMap<TrackerName, Tracker>();

    /**
     * Google Analytics App Tracker.
     */
    private Tracker appTracker;

    /**
     * Google Analytics Global Tracker.
     */
    private Tracker globalTracker;

    /**
     * Google Analytics Ecommerce Tracker.
     */
    private Tracker ecommerceTracker;

    /**
     * If the game has been started.
     */
    private boolean isStarted = false;

    /**
     * Advertisement View.
     */
    protected AdView adView;

    /**
     * Interstitial Advertisement.
     */
    protected InterstitialAd interstitialAd;

    /**
     * Game View.
     */
    protected View gameView;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        if(this.isStarted) {
            return;
        } else {
            this.isStarted = true;
        }

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        super.onCreate(savedInstanceState);

        this.setTitle("Cheeky Chameleon");

        this.appTracker = this.getTracker(TrackerName.APP_TRACKER);
        this.globalTracker = this.getTracker(TrackerName.GLOBAL_TRACKER);
        this.ecommerceTracker = this.getTracker(TrackerName.ECOMMERCE_TRACKER);

        this.appTracker.enableAdvertisingIdCollection(true);
        this.globalTracker.enableAdvertisingIdCollection(true);
        this.ecommerceTracker.enableAdvertisingIdCollection(true);

        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
        config.useAccelerometer = false;
        config.useCompass = false;
        config.useWakelock = true;
        config.hideStatusBar = true;
        config.useImmersiveMode = true;

        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

        RelativeLayout layout = new RelativeLayout(this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        layout.setLayoutParams(params);

        this.createInterstitialAd();

        this.createAdView();
        layout.addView(this.adView);

        this.createGameView(config);
        layout.addView(this.gameView);

        this.setContentView(layout);
        this.startAdvertising();
    }

    @Override
    public void onStart() {
        super.onStart();
        GoogleAnalytics.getInstance(this).reportActivityStart(this);
        GoogleAnalytics.getInstance(this).getLogger()
        .setLogLevel(LogLevel.INFO);

        this.googleApiClient = new GoogleApiClient.Builder(this)
        .addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN)
        .addApi(Games.API).addScope(Games.SCOPE_GAMES)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .build();
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("Stop");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GoogleAnalytics.getInstance(this).reportActivityStop(this);
        this.googleApiClient.disconnect();
        System.out.println("Destroy");
    }

    /**
     * Create AdView.
     *
     * @return AdView.
     */
    private void createAdView() {
        this.adView = new AdView(this);
        this.adView.setAdSize(AdSize.SMART_BANNER);
        this.adView.setAdUnitId(AndroidLauncher.BANNER_ADMOB_UNIT_ID);
        this.adView.setId(12398);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        this.adView.setLayoutParams(params);
        this.adView.setBackgroundColor(Color.WHITE);
    }

    /**
     *  Create fullscreen AdView.
     */
    private void createInterstitialAd() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                interstitialAd = new InterstitialAd(AndroidLauncher.this);
                interstitialAd.setAdUnitId(AndroidLauncher.FULLSCREEN_ADMOB_UNIT_ID);

                AdRequest adRequest = new AdRequest.Builder().build();
                interstitialAd.loadAd(adRequest);
            }
        });
    }

    @Override
    public void loadInterstitialAdvert() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AdRequest adRequest = new AdRequest.Builder().build();
                interstitialAd.loadAd(adRequest);
            }
        });
    }

    /**
     * Create GameView.
     *
     * @param config AndroidApplicationConfiguration.
     * @return View.
     */
    private void createGameView(AndroidApplicationConfiguration config) {
        this.gameView = this.initializeForView(new CheekyChameleon(this), config);

        this.gameView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        params.addRule(RelativeLayout.ABOVE, adView.getId());
        this.gameView.setLayoutParams(params);
    }

    /**
     * Start Advertising.
     *
     * @param adView AdView.
     */
    private void startAdvertising() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
                   AdRequest adRequest = adRequestBuilder.build();
                   adView.setAdListener(new AdListener() {
                       @Override
                       public void onAdFailedToLoad(int error) {
                            System.out.println("Error: " + error);
                       }
                   });
                   adView.loadAd(adRequest);
            }
        });
    }

    @Override
    public void setTrackerScreenName(String name) {
        this.globalTracker.setScreenName(name);
        this.globalTracker.send(new HitBuilders.AppViewBuilder().build());
        System.out.println("Tracking screen: " + name);
    }

    /**
     * Get google analytics tracker.
     *
     * @param trackerName TrackerName.
     * @return Tracker.
     */
    public synchronized Tracker getTracker(TrackerName trackerName) {
        if (!this.trackers.containsKey(trackerName)) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);

            Tracker tracker = (trackerName == TrackerName.APP_TRACKER) ? analytics
                    .newTracker(R.xml.app_tracker)
                    : (trackerName == TrackerName.GLOBAL_TRACKER) ? analytics
                            .newTracker(R.xml.global_tracker) : analytics
                            .newTracker(R.xml.ecommerce_tracker);
            tracker.enableAdvertisingIdCollection(true);
            this.trackers.put(trackerName, tracker);
        }

        return this.trackers.get(trackerName);
    }

    /**
     * Enum used to identify the tracker that needs to be used for tracking.
     *
     * A single tracker is usually enough for most purposes. In case you do need
     * multiple trackers, storing them all in Application object helps ensure
     * that they are created only once per application instance.
     */
    public enum TrackerName {
        APP_TRACKER, // Tracker used only in this app.
        GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
        ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a company.
    }

    @Override
    public void displayInterstitialAdvert() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(interstitialAd.isLoaded()) {
                    interstitialAd.show();
                } else {
                    AdRequest adRequest = new AdRequest.Builder().build();
                    interstitialAd.loadAd(adRequest);
                    interstitialAd.show();
                }
            }
        });
    }

    @Override
    public void signInGooglePlayServices() {
        if(!this.isResolvingSignInError) {
            this.googleApiClient.connect();
        }
    }

    @Override
    public void signOutGooglePlayServices() {
        this.googleApiClient.disconnect();
    }

    @Override
    public boolean isSignedInGooglePlayServices() {
        return this.googleApiClient.isConnected();
    }

    @Override
    public void displayAchievements() {
        if(this.googleApiClient.isConnected()) {
            this.startActivityForResult(Games.Achievements.getAchievementsIntent(this.googleApiClient), AndroidLauncher.REQUEST_ACHIEVEMENTS);
        } else {
            this.googleApiClient.connect();
        }
    }

    @Override
    public void displayLeaderboards() {
        if(this.googleApiClient.isConnected()) {
            this.startActivityForResult(Games.Leaderboards.getLeaderboardIntent(this.googleApiClient,
                    AndroidLauncher.LEADERBOARD_ID), AndroidLauncher.REQUEST_LEADERBOARD);
        } else {
            this.googleApiClient.connect();
        }
    }

    @Override
    public void submitScore(int score) {
        if(this.googleApiClient.isConnected()) {
            System.out.println("Submiting score: " + score);
            Games.Leaderboards.submitScore(this.googleApiClient, AndroidLauncher.LEADERBOARD_ID, score);
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if(this.isResolvingSignInError) {
            return;
        } else if (result.hasResolution()){
            try {
                this.isResolvingSignInError = true;
                result.startResolutionForResult(this, AndroidLauncher.REQUEST_RESOLVE_ERROR);
                System.out.println("Failed to connect to Google Play Services, Resolving");
            } catch(SendIntentException exception) {
                this.googleApiClient.connect();
            }
        } else {
            GooglePlayServicesUtil.showErrorDialogFragment(result.getErrorCode(), this, AndroidLauncher.REQUEST_RESOLVE_ERROR);
            this.isResolvingSignInError = false;
            System.out.println("Failed to connect to Google Play Services: " + result.getErrorCode());
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        System.out.println("Connected to Google Play Services");
    }

    @Override
    public void onConnectionSuspended(int number) {
        System.out.println("Google Play Services connection suspended");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == AndroidLauncher.REQUEST_RESOLVE_ERROR) {
            this.isResolvingSignInError = false;

            if (resultCode == RESULT_OK) {
                if (!this.googleApiClient.isConnecting() &&
                        !this.googleApiClient.isConnected()) {
                    this.googleApiClient.connect();
                }
            } else {
                System.out.println("Sign in failed: " + resultCode);
            }
        } else if(requestCode == AndroidLauncher.REQUEST_ACHIEVEMENTS) {
            if (resultCode != RESULT_OK && resultCode != RESULT_CANCELED) {
                Toast.makeText(this, "Failed to show achivements", Toast.LENGTH_SHORT).show();
                System.out.println("Failed to display achievements.");
            }
        }
    }
}

```

This is my AndroidManifest.xml:

```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ifs_studios.cheekychameleon.android"
    android:versionCode="29"
    android:versionName="0.4.1" >

    <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="com.android.vending.BILLING" />
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.WRITE_GSERVICES"/>

    <application
        android:allowBackup="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name="com.ifs_studios.cheekychameleon.android.AndroidLauncher"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

        <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
        <meta-data
        android:name="com.google.android.gms.analytics.globalConfigResource"
        android:resource="@xml/global_tracker" />
        <meta-data android:name="com.google.android.gms.games.APP_ID"
        android:value="@string/app_id" />
    </application>
</manifest>

```

From the output of the LogCat I have no clue what the problem could be. I have tested this on an Xperia U and Xperia Z1 and the problem still persists. Thanks for your help.

# Answer
After days of stress, I've finally fixed the problem. After performing a backtrace on the main thread I discovered the program came to a halt when trying to load the Google Analytics trackers. This is the thread backtrace:

> at com.google.android.gms.analytics.ae.getLogger(Unknown Source)
> at com.google.android.gms.analytics.ae.W(Unknown Source)
> at com.google.android.gms.analytics.z$a.f(Unknown Source) at com.google.android.gms.analytics.n.a(Unknown Source)
> at com.google.android.gms.analytics.n.x(Unknown Source)
> at com.google.android.gms.analytics.GoogleAnalytics.eZ(Unknown Source)
> at com.google.android.gms.analytics.GoogleAnalytics.(Unknown Source)
> at com.google.android.gms.analytics.GoogleAnalytics.(Unknown Source)
> at com.google.android.gms.analytics.GoogleAnalytics.getInstance(Unknown Source)

I then did some research on this result. It appears to be a bug caused when trying to load the trackers from an xml file. This bug is discussed in more detail here:

To prevent this bug, I no longer load the trackers from their corrosponding xml files by removing this line in the AndroidManifest.xml:

```
<meta-data
        android:name="com.google.android.gms.analytics.globalConfigResource"
        android:resource="@xml/analytics_global_config" />

```

Problem fixed, thanks guys.
> 2 votes

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


# Question
Title: Vertex<>Layout mis-match within PIX(Graphics Debugger)
There's more than a screen-full of code to specify the actual vertex data, the inputlayout, and the shader signature...

**Misleading symptoms:**
Then, it does whatever it wants, anyway.

I can "cause it to rearrange them", but it never puts them in the order it was told to (3 different times/ways). The actual vertex data matches both slot layouts, but is jumbled as soon as I need it; fun.

Edit: **Please, at least, explain why the left panel doesn't match the right panel.** Trying to make it rearrange them doesn't even produce linear results. I.e. if I move COLOR somewhere else, it moves it, but it could end up anywhere, possibly bumping the offset for WORLD and/or anything else.

# Answer
Like most recent games, the developers clearly spent more time making it pretty than making it good. As of this posting, the panel on the right does not correspond to anything real. The data was always correct and in-place.
> 0 votes

---
Tags: directx11
---


# Question
Title: Instantiate prefab randomly but not in already occupied position
I want to generate bubbles randomly on screen. When a bubble is generated in one place then other bubbles should not be generated near its radius 1 area, so they can not collide or trigger with any other bubbles.

How can I do it ?

```
public void GenerateBubble ()
{
    newBubbleXPos = Random.Range (-7, 7);
    newBubbleYPos = Random.Range (-3, 3);
    bubbleClone = (GameObject)Instantiate (bubblePrefab, new Vector3 (newBubbleXPos, newBubbleYPos, 0), Quaternion.identity);
    UIManager.instance.ChangeBubbleSprite (bubbleClone);
    bubbleList.Add (bubbleClone);
    if (bubblePosList.Contains (bubbleClone.transform.position)) {
        bubbleClone.transform.position=new Vector3(Random.Range (-7,7),Random.Range (-3,3),0);
    }
    bubblePosList.Add (bubbleClone.transform.position);
    bubbleClone.transform.parent = UIManager.instance.CurrentLevel.transform;
    GLOBALS.bubbleCounter++;
}

```

In this code every bubble is generated in a different position, but they can collide with other bubbles. I want to generate new bubbles not at the same position. My bubble colliders's radius is 1.

# Answer
> 0 votes
I have found Answer :

```
  public List<GameObject> bubbleList = new List<GameObject> ();
    private int newBubbleXPos;
    private int newBubbleYPos;

public void GenerateBubble ()
    {
        bool locationInvaild = true;
        while (locationInvaild) {
            newBubbleXPos = Random.Range (-8, 8);
            newBubbleYPos = Random.Range (-4, 4);
            currentPosition = new Vector3 (newBubbleXPos, newBubbleYPos, 0);
            locationInvaild = false;
            for (int i=0; i<bubbleList.Count; i++) {
                if (Vector3.Distance (bubbleList [i].transform.position, currentPosition) < 2.5f * radius) {
                    locationInvaild = true;
                    break;
                }
            }
        }
        bubbleClone = Instantiate (bubblePrefab, new Vector3 (newBubbleXPos, newBubbleYPos, 0), Quaternion.identity) as GameObject;
        bubbleList.Add (bubbleClone);
    }

```

# Answer
> 1 votes
There you go.

1. You need to check against all of the positions
2. Compute the distance between them and check whether it's valid or not
3. If everything fails because there are too much bubbles, you need to finish it; whether generating the bubble or deciding not to do it.

Here:

```
public void GenerateBubble ()
{
    float validDistance = 1.0f;
    bool isValidPos = false;
    int tryouts = 100;
    Vector3 newPos = new Vector3();
    while (!isValidPos)
    {
        tryouts--;
        isValidPos = true;
        float newBubbleXPos = Random.Range (-7f, 7f);
        float newBubbleYPos = Random.Range (-3f, 3f);
        Vector3 newPos = new Vector3(newBubbleXPos, newBubbleYPos);
        foreach (Vector3 p in bubblePosList)
        {
            Vector3 direction = p - newPos;
            float sqrDistance = direction.sqrMagnitude;
            if (sqrDistance < validDistance * validDistance)
            {
                isValidPos = false;
                // no need to check further, but generate new position
                break;
            }
        }
        // you don't want an infinite loop when things go unexpectedly wrong
        // you could choose between one the following approaches
        // approach 1: don't generate anything
        if (tryouts == 0 && !isValidPos)
            return;
        // ******************************
        // approach 2: get the last position generated and go with it
        if (tryouts == 0 && !isValidPos)
            break;
        // ******************************
    }
    GameObject bubbleClone = (GameObject)Instantiate (bubblePrefab, newPos, Quaternion.identity);
    UIManager.instance.ChangeBubbleSprite (bubbleClone);
    bubbleList.Add (bubbleClone);
    bubblePosList.Add (bubbleClone.transform.position);
    bubbleClone.transform.parent = UIManager.instance.CurrentLevel.transform;
    GLOBALS.bubbleCounter++;
}

```

# Answer
> 0 votes
Your `if` should probably be a `do...while` (what happens if you are really unlucky and you get another invalid coordinate?).

For the radius, if you maintain a list of bubbles placed, then check whether you new point is within 1 of any of them, then choose another number

E.g your code might look something like:

```
public void GenerateBubble ()
{
    do
    {
         newBubbleXPos = Random.Range (-7, 7);
         newBubbleYPos = Random.Range (-3, 3);
         bool bubbleTooClose = false;
         foreach(GameObject existingBubble in bubbleList)
         {
             float Distance = (existingBubble.transform.position - new Vector3(newBubbleXPos, newBubbleYPos, 0)).sqrMagnitude;
             if(Distance < 1)
             {
                 bubbleTooClose = true;
                 break;
             }
         }

         if(!bubbleTooClose)
         {
             break;
         }
     }
     while(true);

     // now can spawn the bubble with the positions as no bubbles too close
     // remember to add to bubbleList
}

```

Note, we can use `sqrMagnitude` rather than `magnitude` since 1 x 1 = 1. If you wanted a different radius, you would need to square the radius. E.g. if you didn't want bubbles within 2 units of any others, you would check `if(Distance < 2 * 2)`

---
Tags: unity, unityscript
---


title: Use spritesheet frames as particles?

text:
# Question
Title: Use spritesheet frames as particles?
I want to use frames from a spritesheet as particles for my emitter.

I load my spritesheet with :

```
game.load.spritesheet('particles_sheet', 'http://stuff.lck.io/luckyslot/sprite_sheet.png', 50, 50, 6);

var emitter = game.add.emitter(game.world.centerX, canvas_height, 80);

```

And i need some code to load the right frame at random :

```
emitter.makeParticles('particles_sheet');

```

Any idea?

# Answer
I used this code to generate a simple array with consecutive values like \[0,1,2,3,4,5\] starting at 0

```
var particules = 6;
var _pArray = Array.apply(null, {length: particules}).map(Number.call, Number)

```

and then i used this array as a second param in the makeParticles method :

```
emitter.makeParticles('logo_sheet', _pArray );

```

Works perfectly !
> 1 votes

---
Tags: sprites, spritesheet, particles, phaser
---


# Question
Title: Texture packer and 2d game sprite sheet creation
I am developing a game in Unity3D. I have a bunch of images which display the character animations. I decided to use texture packer to reduce the amount of individual images. I create one sprite sheet with type `multiple` containing all the images of my animation.

After creating the sprite sheet the animation broke up. The images start to overlap and not animate in the same speed despite the fact that before the animation was working fine but heavy on my app.

The spritesheet was created by importing all my assets for every animation into texture packer and export it into png file with a dimension of: 4096x4096

# Answer
Unity needs some way of "finding" the animation frames in the sprite sheet. What you currently see is that this information is not property provided.

There are several ways to set this up. The easiest way is to use TexturePacker Importer. It reads a data file provided by TexturePacker and slices the sprite sheets. Here's a micro tutorial.

Another way would be to create all frames with identical sizes and tell Unity how big they are. Or use some 3rd party framework like 2dtoolkit ...

So which way are you using to import the data?

Btw. 4096x4096 might give you trouble on several platforms. While this might not be your current problem it has a good change to result in jittering animations due to limitations in floating point precision in OpenGL. I would really recommend using 2048 or smaller sprite sheets.
> 1 votes

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


title: Apply shader to only a part of a sprite

text:
# Question
Title: Apply shader to only a part of a sprite
I'm trying to make an image blur when a transparent image overlays it, I am wanting it only to blur the section that is being overlayed. So if half of the original image is not being overlapped, that half is not blurred but the rest is.

Un-blurred - Not overlapping https://i.stack.imgur.com/K9jsk.png

Fully Blurred - partially overlapping https://i.stack.imgur.com/zHLup.png

Game1.cs

```
namespace NewShaderTutorial
{
  /// <summary>
  /// This is the main type for your game
  /// </summary>
  public class Game1 : Microsoft.Xna.Framework.Game
    {
      GraphicsDeviceManager graphics;
      SpriteBatch spriteBatch;

    Effect blur;
    Texture2D surge;
    Rectangle surgeRectangle;
    Texture2D bubble;
    Rectangle bubbleRectangle;
    private bool overlapping;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        surge = Content.Load<Texture2D>("surge");
        surgeRectangle = new Rectangle(250, 250, surge.Width, surge.Height);

        bubble = Content.Load<Texture2D>("Bubble - Red");
        bubbleRectangle = new Rectangle(250, 250, bubble.Width, bubble.Height);

        blur = Content.Load<Effect>("blur");

        // TODO: use this.Content to load your game content here
    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        if (Keyboard.GetState().IsKeyDown(Keys.Left))
            bubbleRectangle.X--;
        if (Keyboard.GetState().IsKeyDown(Keys.Right))
            bubbleRectangle.X++;
        if (Keyboard.GetState().IsKeyDown(Keys.Up))
            bubbleRectangle.Y--;
        if (Keyboard.GetState().IsKeyDown(Keys.Down))
            bubbleRectangle.Y++;

        blur.Parameters["blur"].SetValue(0.015f);

        Overlapping();

        // TODO: Add your update logic here

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        if (overlapping == true)
        {

            spriteBatch.Begin(0, null, null, null, null, blur);
            spriteBatch.Draw(surge, surgeRectangle, Color.White);
            spriteBatch.End();
            //     spriteBatch.Begin(0, null, null, null, null, blur);
            spriteBatch.Begin();
            spriteBatch.Draw(bubble, bubbleRectangle, Color.White);
            spriteBatch.End();
        }
        else
        {
            spriteBatch.Begin();
            spriteBatch.Draw(surge, surgeRectangle, Color.White);
            spriteBatch.Draw(bubble, bubbleRectangle, Color.White);
            spriteBatch.End();
        }

        // TODO: Add your drawing code here

        base.Draw(gameTime);
    }

    public void Overlapping()
    {
        float surgeDimensionX = surgeRectangle.X + surge.Width;
        float surgeDimensionY = surgeRectangle.Y + surge.Height;
        float bubbleDimensionX = bubbleRectangle.X + bubble.Width;
        float bubbleDimensionY = bubbleRectangle.Y + bubble.Height;

        if ((surgeRectangle.X >= (bubbleRectangle.X) && ((surgeRectangle.X <= (bubbleDimensionX))) && (surgeRectangle.Y >= (bubbleRectangle.Y)) && (surgeRectangle.Y <= (bubbleDimensionY))))
        {
            overlapping = true;
        }
        else
        {
            overlapping = false;
        }
        Console.WriteLine(overlapping);
    }
}

```

Blur.fx class

```
// TODO: add effect parameters here.
sampler TextureSampler;

float blur = 0.0015;

struct PixelInput
{
    float2 TexCoord : TEXCOORD0;
};

float4 PixelShaderFunction(PixelInput input) : COLOR0
{

    float4 color = tex2D(TextureSampler,
    float2(input.TexCoord.x+blur, input.TexCoord.y+blur));
color += tex2D( TextureSampler,
    float2(input.TexCoord.x-blur, input.TexCoord.y-blur));
color += tex2D( TextureSampler,
    float2(input.TexCoord.x+blur, input.TexCoord.y-blur));
color += tex2D( TextureSampler,
    float2(input.TexCoord.x-blur, input.TexCoord.y+blur));

color = color / 4;
    return color;
}

technique Default
{
    pass P0
    {
        // TODO: set renderstates here.

        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

So I'm wanting to get the partially overlapping part to only blur the section that is being overlapped not the whole sprite. Any help would be great, as I've been stuck on this for awhile.

Thanks!

# Answer
First draw your bubbles with basic shader to RenderTarget2D texture. Next draw sprites shat should be blured with custom shader and pass it as BlurMapTexture paramether. In this shader add sampler for blur map:

```
texture BlurMapTexture;
sampler2D blurMapSampler = sampler_state
{
    Texture = (BlurMapTexture);
    MagFilter = Point;
    MinFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

```

Check is pixel from blur map is transparent then there should be no blur, if not transparent then blur should be applied.

```
float4 PixelShaderFunction(PixelInput input) : COLOR0
{
    float4 color;
    float4 blurMapColor = tex2D(blurMapSampler, texture)
    if (blurMapColor.a == 0)
    {
        color = tex2D(TextureSampler, input.TexCoord);
    }
    else
    {
        color = tex2D(TextureSampler,
            float2(input.TexCoord.x + blur, input.TexCoord.y + blur));
        color += tex2D(TextureSampler,
            float2(input.TexCoord.x - blur, input.TexCoord.y - blur));
        color += tex2D(TextureSampler,
            float2(input.TexCoord.x + blur, input.TexCoord.y - blur));
        color += tex2D(TextureSampler,
            float2(input.TexCoord.x - blur, input.TexCoord.y + blur));
        color = color / 4;
    }

    return color;
}

```

And then just draw texture with bubbles above blured image. I think it should works.

**Update**

I'm upload example project on google drive.
> 1 votes

---
Tags: xna, c#, shaders, xna-4.0, graphic-effects
---


# Question
Title: How do I convert a greyscale height map to .3ds format?
I was given some height maps to use for game development, but they are in grayscale PNG format. How can I convert them to 3DS format?

# Answer
As tkausl suggests, it should be trivial to program a simple tool:

* Construct 2D grid
* Apply heights from the image
* Write it to OBJ format file
* Import into 3DMax
> 2 votes

# Answer
I haven't worked with 3DMax in several years, but it should be pretty simple to generate a 2D grid primitive/object and apply displacement texture (your heightmap image) to it along the vertical axis. Then freeze the geometry.
> 0 votes

# Answer
If you need to, you could use the Assimp file import library's 3ds export function to create the 3ds files directly.

The procedure would be as follows:

* Load Image
* Process it into a vertex and index list.
* Add those to the aiScene structure.
* Export it using the 3ds exporter.

Also, if you are writing your game's code, or if the engine supports it, consider loading the image directly to the game and using it there. If there is a specific function like that, it usually should be much faster than simple model files, due to 2 reasons:

* When rendering you don't have to render Triangles but Triangle strips.
* Collision engines usually implement heightfield collision with a simpler test than for complex meshes.
> 0 votes

---
Tags: image, 3dsmax, file-format, heightmap
---


title: Why encode floats in RGBA?

text:
# Question
Title: Why encode floats in RGBA?
Working on some effects that require **depth** (Z) data in Unity, I saw that these use a method to store the depth data encoded in the RGBA channels of a regular texture.

```
half4 frag(v2f i) : SV_Target
{
    float d = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, i.uv.xy);
    d = Linear01Depth(d);

    return EncodeFloatRGBA(d);
}

```

**Main question**: **why do this?** Why not just store the result in a single-channel 16-bit float (R16F) texture?

**Sub question:**

What also surprises me is that the data is used as if these were independent RGBA channels. (the `_EncodedDepth` below contains the output of function above)

```
half4 color = float4 (0,0,0,0);
color += 0.40 * tex2D (_EncodedDepth, i.uv);

```

Then *after that*, information is *decoded* into a float value again.

```
float4 depth = tex2D(_ProcessedDepth, i.uv);
depth.a = DecodeFloatRGBA(hrDepth);
// do something with depth.a

```

Does this mean that linear operations applied to the encoded values are equivalent to linear operations applied to the original float? I.e.:

```
DecodeFloatRGBA( 0.5 * EncodeFloatRGBA(d) ) == 0.5 * d   // really?

```

# Answer
> 3 votes
Hardware has not always supported floating-point texture formats. In fact, D3D has not always supported depth textures.

When you see this sort of thing, it is usually because the application is trying to support an older API or older hardware. To store depth on these systems, they must be converted to fixed-point and packed into 4 channels of a traditional unsigned normalized (UNORM) texture.

I do not know how `EncodeFloatRGBA (...)` is implemented, but it is probably a dot product and a few divisions by numbers like **255.0** and **65535.0**.

---
Tags: opengl, unity, shaders, cg
---


title: OpenGL Indexed VBOS?

text:
# Question
Title: OpenGL Indexed VBOS?
I'm a little confused with using indexed vbos in opengl. I understand that different each vertex can only have one uv. How would it be possible to map a texture onto a 3d object if you can't "unwrap" the object? Here's what I mean:

3D pyramid with 4 vertices, 4 uv coordinates

3D pyramid unwrapped, 3 shared vertices, 3 unshared vertices

It is impossible to map a texture to it without having more uv coordinates, right?

Is there a solution to this problem while still using indexed vbos? Can I make this work with only 4 vertices?

# Answer
> 2 votes
You can, however, not if you'r vertices use distinct UV's for each side.

Your example is, well, not the best. To use indexed VBOs, you need a few more vertices. For example, take a look at this Picture (found in google):

As you see on the right, a lot of faces share their vertices and each vertex uses the same UV. The more vertices your model has, the more vertices you can (probably) share, *but*, it will (almost) **never** work to have the exact same amount of shared vertex+UV pairs as you have unique vertices.

---
Tags: opengl, c++
---


# Question
Title: How to correctly import 3D max files into Unity3d?
I am trying to import a downloaded 3D max (.3DS) object into Unity3D and preserve the textures correctly. I've tried to select the .3DS-file and its jpg-files and dragged and dropped it into Unity3D. Everything works fine, and the object can be added to the scene. But I am unable to add the texture to the object. I have tried to drag and drop it like you can do with other kinds of objects, but it won't work on the imported objects.

# Answer
The right way to apply a texture to a Mesh in Unity is creating a **Material** and then assigning your texture to the Albedo/Color map attribute of the Material, then you can drag and drop the Material into your desired Mesh/Object in the Scene.

Material Inspector in Unity 5:

Cheers!
> 1 votes

---
Tags: unity
---


# Question
Title: Strategy for keeping a primitive facing the viewport?
Using XNA, c#.

I'm writing a stellarium-type of program-- well, trying to :-) -- and I have a 'sun' texture that I'll be pasting onto triangle primitives. I'll also be floating some text above each node, which will probably be on the primitive as well.

My issue is how to force the primitives to always be facing the camera, despite rotations and movements of the viewport. I'm going through my XNA programming books, but there's no obvious solution. I'd appreciate a pointer in the right direction.

Note: I'm not using 3D models, so AFAIK there's no Matrix to work with. I have 3 vector3's that define a triangle, and I guess I have to modify their addresses on each update to face the camera. That seems pretty intensive, so I'm thinking I may be missing something obvious.

# Answer
> 1 votes
Assuming you created your triangle strip in Model Space.

Use Matrix.CreateBillboard to create a transformation matrix that will rotate your triangle strip towards the camera. Note the below values should be in World Space.

```
public static Matrix CreateBillboard (
         Vector3 objectPosition,
         Vector3 cameraPosition,
         Vector3 cameraUpVector,
         Nullable<Vector3> cameraForwardVector
)

```

Apply this matrix to using `Vector3.Transform(point, billboardMatrix);` before applying the transformations you use to convert into world space (you might not have gotten this far yet).

PS: Even if you are not using models familiarize yourself with the existing spaces it will save you a lot of headache later. Also people use HLSL shaders because billboarding is typically used for things like grass, trees, particles and as such performance is major a concern.

# Answer
> 0 votes
The default shader is not designed for this. You will need either a custom shader or need to manually update the positions. This second option will have low performance, especially for large numbers of stars.

The standard shader is:

```
// in_p is the position from the vertex buffer
p_camera = modelview * in_p
out_p = projection * p_camera
// out_p goes to rasterizer as clip-space position

```

The shader you need is:

```
p_camera = modelview * in_p
// in_uv is in [0,1]x[0,1]
// in_size is a scalar
p_camera += vec4((in_uv.xy-vec2(0.5,0.5))*in_size, 0, 0);
p_out = projection * p_camera

```

Then you need to set up your vertex data so that in\_p is the same position (the center) of your stars, in\_uv encodes where on the face the vertex is (so if you are using two triangles to make a quad, you would have (0,0), (0,1), (1,0), and (1,1)), and in\_size is the diameter of the star. You will have say four vertices in your buffer all with the same in\_p and in\_size, but the four different uv coords, and the index buffer will make two triangles out of them. This repetition is not an performance concern.1 This works because in camera space, adding to x or y will move the vertex orthogonally to the view direction.

Be careful with backface culling and accidentally inverting the order of your faces. If your modelview matrix is only a view matrix, i.e. only have rotations and translations, then sizes in camera space and world space match up. A final issue is this technique will have the textures always facing up from the cameras perspective, which will look weird if they are not radially symmetric.

1 If it is, you are doing something else very wrong, like trying to draw many more stars than pixels or killing your vertex pipeline. If you really feel you need to solve this, you will need geometry shaders.

# Answer
> 0 votes
Try see this tutorial, it can be what are you looking for.

P.S. I'm test my implementation of it with 1,000,000 enderman eyes (original 16x16 pixels texture) and performance was pretty good.

---
Tags: xna, c#
---


title: Weird rendering of bounding box

text:
# Question
Title: Weird rendering of bounding box
I'm trying to make a bounding rect for my bullet which is in space invader game. I'm using marmalade, and the bounding rect seems translated and doesn't bound the bullet at all, however the math is correct. Here is a video of the behavior and a snippet of code http://youtu.be/SbjMPKQ7ilE

```
void Bullet::Render()
{
    if (ShipBullet == nullptr)
        return;

    if (Visible)
    {
        Transform.SetIdentity();

        // Build transform
        Transform.SetRot(Angle);
        Transform.ScaleRot(Scale);
        Transform.SetTrans(Position);
        Iw2DSetTransformMatrix(Transform);
        Iw2DSetColour(Colour);

        CIwFVec2 pos = Transform.t;
        BoundingRect.x = pos.x;
        BoundingRect.y = pos.y;
        BoundingRect.w = (float)ShipBullet->GetWidth();
        BoundingRect.h = (float)ShipBullet->GetHeight();

        // Render image
        if (ShipBullet != 0)
        {
            int x = -(ShipBullet->GetWidth() / 2);
            int y = -(ShipBullet->GetHeight() / 2);
            Iw2DDrawImage(ShipBullet, CIwFVec2(x, y), CIwFVec2(ShipBullet->GetWidth(), ShipBullet->GetHeight()));
        }

// render bounding rect
#if 1
        Iw2DSetColour(0xff0000ff); // Set red
        Iw2DDrawRect(CIwFVec2(BoundingRect.x, BoundingRect.y),
            CIwFVec2(ShipBullet->GetWidth(),ShipBullet->GetHeight()));
#endif

    }
}

```

# Answer
> 0 votes
You have to use the same coordinates for both of your objects.

```
void Bullet::Render()
{
    if (ShipBullet == nullptr)
        return;

    if (Visible)
    {
        Transform.SetIdentity();

        // Build transform
        Transform.SetRot(Angle);
        Transform.ScaleRot(Scale);
        Transform.SetTrans(Position);
        Iw2DSetTransformMatrix(Transform); // Set a 2D transform to apply to all
                                           // subsequent drawing operations. This
                                           // is taken into considration for the
                                           // Iw2DDrawImage and Iw2DDrawRect calls,
                                           // bellow.
        Iw2DSetColour(Colour);

        CIwFVec2 pos = Transform.t;
        BoundingRect.x = pos.x;
        BoundingRect.y = pos.y;
        BoundingRect.w = (float)ShipBullet->GetWidth();
        BoundingRect.h = (float)ShipBullet->GetHeight();
        // I don't know where but the BoundingRect must be used somewhere else.

        // You have already applied the transformation with the position of your
        // object, which you consider as being the center. You now have to offset
        // the graphics by its size to draw it around the center.
        int x = -(ShipBullet->GetWidth() / 2);
        int y = -(ShipBullet->GetHeight() / 2);

        // Draw the image, x/y is top left, per the documentation (http://api.madewithmarmalade.com/group__iw2dImages.html#ga60855d305af26248dd9eb71fcb4c656d)
        Iw2DDrawImage(ShipBullet,
            CIwFVec2(x, y),
            CIwFVec2(ShipBullet->GetWidth(), ShipBullet->GetHeight()));

// render bounding rect
#if 1
        Iw2DSetColour(0xff0000ff); // Set red
        Iw2DDrawRect(
            CIwFVec2(x, y),
            CIwFVec2(ShipBullet->GetWidth(),ShipBullet->GetHeight()));
#endif

    }
}

```

From what I understand from marmalade, a call to Iw2DSetTransformMatrix(Transform) sets the transformation for all your subsequent calls. Then you have to use the same data if you want to have both your objects at the same location.

Edit:

See my comments in the code, and more explanation:

You could have used the x/y of the Position and of the BoundingBox *if* you did not use the position in the calculation of the Transform (and the subsequent call to Iw2DSetTransformMatrix). By using the x/y of the bounding box, you were actually moving your bounding box twice: one because of the position/call-to-Iw2DSetTransformMatrix, and once because you were offsetting it by it's position again.

---
Tags: c++, marmalade
---


# Question
Title: How to use multiple custom vertex attributes in OpenGL
My code currently uses glBindAttribLocation and glVertexAttribPointer to specify two custom vertex attributes in indices 6 and 7. This seems to work fine, but I wish to add another attribute and no index other than 6 or 7 will work - the shader instead acts like the attribute is always set to a value of 0.

I'm using gl\_Vertex, gl\_Normal, gl\_Color and gl\_MultiTexCoord0, and apparently some nVidia thing means indices 0, 2, 3 and 8 are off limits, but that should still leave other indices. I don't use gl\_SecondaryColor or gl\_FogCoord anywhere in my code or shaders for example, but indices 4 and 5 still don't work.

If I change graphics cards for an ATI one which supports more than 16 attributes, then indices 16+ work fine, but I want to support cards with only 16 attributes.

# Answer
For "modern" OpenGl, it's easiest to use all "custom" attributes, instead of a mix of classic built-in ones and your own.

Add your own vec3 for "positionXyz" or whatever you'd like to call it, and so on.

(For myself, I never pre-assign locations, just let OpenGl pick them has seemed sufficient for needs.)
> 1 votes

---
Tags: opengl
---


# Question
Title: Unity shaders: best way of handling data structures
I'm working on a shader in Unity that uses a Binary Tree to store some precomputed values, this binary tree should be available to the shaders and would ideally also be constructed on the graphics card (each node in this tree is based on 1 pixel) is there a good way of doing this?

# Answer
> 2 votes
The best way of passing such data to the GPU, using the shaders pipeline, would probably be with a **texture**. Knowing that, your own question answers it: A texture with one pixel for each node of the tree.

---
Tags: unity, shaders
---


# Question
Title: Is there a tool to make a Spritesheet out of 1000 PNG's?
My graphics designer has made graphics in separate PNG files. Is there a clever tool/script that mashes them into a spritesheet?

I could probably code something myself, but why re-invent the wheel :)

# Answer
> 22 votes
Am I the only one who uses SpriteSheetPacker? It's free and open source so you can modify it and learn how it works.

# Answer
> 13 votes
I've been using TexturePacker to create sprites from a folder of PNG images. I'm porting a game originally developed in Flash, so I'm simply exporting each frame of the MovieClip to png and then importing those images in Texture Packer.

Another similar tool is Zwoptex

(The latter is Mac software, but TP has a version for Windows too.)

# Answer
> 6 votes
ImageMagick has a command line utility that can join images into what it calls a "montage." It can be tiring getting the right command line parameters to do what you want, but it's a very powerful and flexible tool. I use it very frequently for building spritesheets.

# Answer
> 6 votes
I have decided to open source my 2D spritesheet and animation tool. It supports automatic sprite selection, combining images, sprite grouping, and multi-sprite animation with rotation.

It is written in Java, the github repo is here: https://github.com/darkFunction/darkFunction-Editor

Website for the project is: http://darkfunction.com/editor

# Answer
> 3 votes
I really like libgdx's (game framework) packer. Maybe a bit cumbersome to set up the framework just for the packer, though.

The packer works great. Read the libgdx texturepacker doc here, and see for yourself. My favourite feature is that is also saves a document with info about all the textures in the big spritesheet/atlas, so you can easily make a script that gets them for you. Libgdx also has this build in, so I can load/display any texture by it's original filename, even though it's in a big atlas. There also exists a GUI for the packer.

Excerpt from a pack-file with info about some textures:

```
ferdige1.png
format: RGBA8888
filter: Nearest,Nearest
repeat: none
mainmenu
  rotate: false
  xy: 2, 2
  size: 800, 480
  orig: 800, 480
  offset: 0, 0
  index: -1
plankeu3
  rotate: false
  xy: 804, 2
  size: 64, 384
  orig: 64, 384
  offset: 0, 0
  index: -1
levelSelect
  rotate: false
  xy: 2, 484
  size: 591, 373
  orig: 591, 373
  offset: 0, 0
  index: -1
plankeu2
  rotate: false
  xy: 870, 2
  size: 64, 256
  orig: 64, 256
  offset: 0, 0
  index: -1

```

# Answer
> 0 votes
I ended up using this Processing script. You can download Processing for free at Processing.org. All files need to be in the same folder, and have a filename ending in a 4 digit number.

```
ArrayList<PImage> images = new ArrayList

<PImage>();

void setup() {
  String folder = "file location ...";
  String file = "file prefix ...";
  String outfile = "output.png";
  int fileCount = 30;
  int cols = 7;
  int rows = 5;

  println("Loadgin...");
  for (int i = 1; i <= fileCount; i++) {
    String number = "" + i;
    if(number.length() == 1) number ="000" + number;
    else if(number.length() == 2) number = "00" + number;
    PImage img = loadImage(folder+file + number +".png");
    images.add(img);
  }

  println("Starting...");
  PImage img = createImage(images.get(0).width * cols, images.get(0).height * rows, ARGB);
  for (int x = 0; x < images.get(0).width; x++) {
    for (int y = 0; y < images.get(0).height; y++) {
      for (int z = 0; z < images.size(); z++) {
        img.set(
          x+images.get(0).width* (z%cols),
          y +images.get(0).height * int(z/cols),
          images.get(z).get(x,y));
      }
    }
  }
  println("Saving...");
  img.save(folder + outfile);
}

```

# Answer
> 0 votes
I use a Photoshop script to make spritesheets, see this article on my blog.

It can make old skool tile grids as well as texture atlases, and can export a custom text file containing image size and position info. It works on PC and Mac, it's open source and written to be extensible.

# Answer
> 0 votes
I don't know if I understood question correcttly but I know the software that operates with textures and makes animation, sprite sheets anf .gif animations. see http://www.spritetools.com/

# Answer
> 0 votes
The Compass framework has a sprite generation tool.

\[Video\]

---
Tags: spritesheet
---


# Question
Title: Unity Collision Difficulties (How do I make a ground in unity with lots of pieces that doesn't have poor collision?)
So I'm working on this game that I came up with the idea for while watching the Unity Roll-a-ball tutorials. So it's probably important to note that I'm extremely new to game design and I don't have a whole lot of experience in programming.

So the game idea that I had is a lot more complex than what it should be for someone who's pretty much completely new to game design, so I guess I'm trying to break it down into smaller bits until I have enough experience to build it into a cohesive game.

Currently what I want to work on is a game where you play as a sphere rolling down a plane with open edges so you can fall off. There are walls that you have to avoid, and if you run into them it will take away from the space between the walls and the edge of the plane. I guess I was sort of thinking of having a sort of similar visual style as bastion in that sense.

The way I thought I would go about this is to break the plane up into smaller squares and then do some programming so that when you run into the walls the smaller squares at the edge of the plane fall off. Though before I could even get to programming I ran into a big problem. Because of the way Unity physics work and the way I built the ground, the player collision with the ground is god awful. When I was just testing it with some basic controls the ball would roll all choppy and if I picked up enough speed it would start to jump. I assume this is because it's colliding with all the edges of the grid system that I built.

Does anyone know of any way I can program the edges to not interact with the player? Or if there's a better way to go about doing this?

# Answer
The best way would be to use a single mesh/collider for your ground and scale it as needed. If that's not possible due to the layout of the level, you could place a single transparent plane with a collider slightly above your grid plane and use that as your "floor" (scaling it down to match the grid underneath). you could then remove the colliders from all of your grid pieces and save some performance.
> 1 votes

---
Tags: unity, collision-detection
---


# Question
Title: How do I properly apply root motion when using a blender exported FBX in Unity?
So I realize the common way for animations to be done is in-place with sliding feet, then control the animation playback to coincide with the character's feet, etc. However, given a scenario such as a chess game, where you'd want to play an animation of the chess piece moving forward, then when it stops you'd want its root position updated so the next animation that played would start from the new "square." Note that this is just an example, and that the same requirement could be in place for a person doing a ground roll, a blobular mass moving forward, etc. Rather than try to type everything I tried here, I have put together a short 8 minute screencap walking through the exact steps I took to replicate the issue in Blender 2.7 and Unity 5.

http://youtu.be/BZll5aisY7k

Basically, the "Apply root motion" option does not work as expected (or at least as I expected). in the end, I'm looking fir a viable way of doing in-place animation in Blender and getting the root motion to be properly applied in Unity.

Let me know if you need any specifics, thanks!

EDIT: A (rather lengthy) tutorial on the 'right way' to do it. I geared it towards novice-level users, so it goes through the modeling, rigging, animating, exporting, and Unity steps, but if you're here looking for the solution to this question, there are annotations pointing to the different sections. https://www.youtube.com/watch?v=yKP2Qy-yKhE

# Answer
> 4 votes
OK, after much button mashing, I figured it out:

If you click on your main FBX object, in the inspector you will find 3 buttons at the top. The ones we care about are Rig and Animations. If you go to Rig and drop down the "Root node" selector, then choose your root bone, it will open up some more options under the Animations button. Go back to the Animations button and pick one of your animations. You will now see a series of Root Transform (Rotation / Position) areas, just under Loop Time. Check Loop time, Uncheck Loop Pose, make sure all the "Bake" options are unchecked, and change all the Root Transform "Based Upon" dropdowns to Original. This is apparently what was screwing me up... some were set to "Root Node Rotation" (seemingly at random), and this was causing me to loop in place or move opposite the root bone direction.

I'll post a new vid here once I make it, showing the correct procedure from start to finish for those searching for a similar issue. Thanks!

---
Tags: unity, blender, skeletal-animation
---


title: Memory game - texture on cards

text:
# Question
Title: Memory game - texture on cards
I'm new with Unity and I'm working on recreating memory game. I found this sample: http://xtasestudios.com/unity/samples (select "Memory"). I decided for C#.

I've created my own card in Blender, added 3 different materials (without textures), also I created flip-flop animations. After importing .blend file in Unity and assigning scripts, textures, animations, positioning camera etc..

Everything works fine, except textures on cards. I can change color on cards, but when I want to see any texture on my card, I see only color, not whole texture. I really have no idea why is this happening and how to fix it.

Any help will be appreciated!

# Answer
In order to see a texture properly on a card, you need to first UV unwrap the mesh in blender.

* Press Tab to get into edit mode on your card object.
* Press A until you have all of your vertices selected
* Press U and do a Smart UV Unwrap
* Bring up a UV/Image editor window.
* Make a new UV image or open your card image.
* Fidget with the UVs until you get it lined up like you want.
* Re-export your object into Unity. It will now have predictable texture results.

I personally like to use the UV window to export my UV layout to an image file that I can open in photoshop and use as a guide for making my textures. Then you could re-use a single card mesh with a single UV layout and just re-assign multiple textures for different cards, knowing they will all line up.
> 1 votes

---
Tags: unity, textures, blender, materials
---


# Question
Title: How do I make my main character move towards an object? LibGDX/Java
What I want to happen is for my player to bounce from spring to another. For example take the illustration below:

Here's my code (what I've tried to do so far). This gets called in an `update()`method

```
public void springCollision(Box containsSpring) {
        // player object
        Player player = ((Player) this.object);
        // first spring
        Spring boxSpring = containsSpring.getSpring();
        // second spring
        Spring platformSpring = containsSpring.getPartnerPlatform().getSpring();
        // if player collides with first spring
        if (player.getRect().overlaps(boxSpring.getRect())) {
            // distance in x between first & second spring
            float dx = platformSpring.getxPos()
                    + platformSpring.getSprite().getWidth()
                    - boxSpring.getxPos() - player.getSprite().getWidth();
            // distance in y between first & second spring
            float dy = platformSpring.getyPos() - boxSpring.getyPos();
            Vector2 directionToSpring = new Vector2(dx, dy);
            // normalise vector then set player speed
            player.setxSpeed(directionToSpring.nor().x);
            player.setySpeed(directionToSpring.nor().y + player.getGravity());
        }
    }

```

What currently happens is that when he jumps onto a spring his jump just continues but in slow motion for some reason. Can anyone see why my algorithm doesn't work? Let me know if the comments are unclear

# Answer
To implement a spring I would do this:

1. On the spring-player collision detection:
    1. Give an impulse to the player toward the desired direction;
    2. Disable the spring;
    3. Let the gravity take care of the rest.
2. Re-enable the spring after one or more conditions:
    * After a certain delay;
    * After the player is no longer colliding with the spring;
    * After the player is sufficiently away from the spring.
> 3 votes

---
Tags: java, 2d, collision-detection, libgdx
---


# Question
Title: How to show a popup with text when a game object is selected?
We're building an FPS game where you walk around a 3D environment and walk up to objects, click, and then a GUI message pops up.

Basically, I've got a character, walking around in 3D space, and is using a raycast to interact with things. However, I can't figure out how to hook on a UI pop up.

I'm writing in C# because that's what the original tutorial is in. I tried checking out tutorials on how to make a pause menu appear (thinking I could just hook a pause pop up to the raycast clicking action) but all the tutorials are in JS or were written prior to Unity 4.6 UI manager implementation.

So any clue on how to do this?

# Answer
> 1 votes
Interaction with the UI, and by the UI is primarily done via events. You can learn about activating code with the UI from the official Unity tutorial on the subject.

However, it sounds like you're more interested in finding out how to show a UI element based on a code event. The easiest way to accomplish this is simply toggling the UI object's `enabled` property.

I'd probably put a script on all the objects you're raycasting at, giving them some information about what should be displayed in the pop up. Something like `MyTextInfoScript` would have a public string called `textForPopUp` that would contain the text the pop up is supposed to display when the raycast hits the object.

For example, when your ray hits an object you're interested in, and you want to activate a pop up, set your pop up canvas element to enabled and set it's text to the text you want to show for that object. You don't show how you're doing the ray casting, but it could be something like:

```
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.up, out hit, maxRayDistance, layerMask))
    popupCanvas.enabled = true;
    MyTextInfoScript textInfo = hit.gameObject.GetComponent<MyTextInfoScript>();
    popupText.text = textInfo.textForPopUp;
}

```

Where `popupCanvas` and `popupText` are references to the canvas for your pop up element and the text component inside the pop up.

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


# Question
Title: Libgdx: different speed on different devices
I am running a simple Libgdx app that I have wrote, on my Android phone and Android tablet and I am getting the unexpected result of having different velocities when a body is moved. To move the body I am using a "drag" movement in this way (snippet):

```
private Body ballBody;
private int ballX1, ballY1;

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    ballX1 = screenX;
    ballY1 = screenY;
    return true;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    Vector2 v2 = new Vector2(ballX1 - screenX, screenY - ballY1);
    v2.scl(0.25f);
    ballBody.setLinearVelocity(v2);
    return true;
}

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

```

Render part with some of my attempts to fix delta-time and FPS:

```
private static final int SCREEN_HEIGHT = 16; //320;
private static final int SCREEN_WIDTH = 24; //480;
private static final int BOX_VELOCITY_ITERATIONS = 6;
private static final int BOX_POSITION_ITERATIONS = 2;
private static final float BALL_RADIUS = 0.1f;
private static final float MAX_FPS = 1 / 60f;
private static final float PIXELS_TO_METERS = 20f;
private static final long ONE_SECOND_NS = 1000000000;

private int maxUpdates = 10;
private long lastTime = System.nanoTime();
private World world = new World(new Vector2(0, -9.8f), true);

@Override
public void render() {
    ballIsNotMoving = ballIsNotMoving();
    if (ballIsNotMoving && ballBody.getPosition().x > landscape2d[20] && ballBody.getPosition().x < landscape2d[28]) {
        newHole();
    } else if (ballBody.getPosition().x > SCREEN_WIDTH + ball.getWidth() / 2 || ballBody.getPosition().x < - ball.getWidth() / 2) {
        resetBallPosition();
    }

    camera.update();
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glClearColor(34/255f, 167/255f, 240/255f, 0);

    fixTimeStep();

    world.step(MAX_FPS, BOX_VELOCITY_ITERATIONS, BOX_POSITION_ITERATIONS);

    shapeRenderer.setProjectionMatrix(camera.combined);

    // Set the sprite's position from the updated physics body location
    ball.setPosition(
            ballBody.getPosition().x - ball.getWidth() / 2,
            ballBody.getPosition().y - ball.getHeight() / 2);

    polySpriteBatch.setProjectionMatrix(camera.combined);
    polySpriteBatch.begin();
    pitch.draw(polySpriteBatch);
    polySpriteBatch.end();

    createStartArea(shapeRenderer);

    fixFPS();

//        debugRenderer.render(world, camera.combined);
}

private boolean ballIsNotMoving() {
    float speedNow = ballBody.getLinearVelocity().len();
    recentSpeed = 0.1f * speedNow + 0.9f * recentSpeed;
    if (recentSpeed < 0.20f) {
        stopBallMovement();
        return true;
    }
    return false;
}

private void fixTimeStep() {
    long time = System.nanoTime();
    long timeDelta = time - lastTime;
    float timeDeltaSeconds = timeDelta / (float) ONE_SECOND_NS;
    lastTime = time;

    // Update the game state in capped time steps (in case we're running too slow)
    int updateCount = 0;
    while (timeDelta > 0 && (maxUpdates <= 0 || updateCount < maxUpdates)) {
        // Update using a time step in seconds
        float updateTimeStep = Math.min(timeDeltaSeconds, ONE_SECOND_NS * MAX_FPS);
        float updateTimeStepSeconds = updateTimeStep / (float) ONE_SECOND_NS;

        world.step(updateTimeStepSeconds, BOX_VELOCITY_ITERATIONS, BOX_POSITION_ITERATIONS);

        timeDelta -= updateTimeStep;
        updateCount++;
    }
}

private void fixFPS() {
    long sleepTime = Math.round((ONE_SECOND_NS / MAX_FPS) - (System.nanoTime() - lastTime));
    if (sleepTime <= 0)
        return;
    long prevTime = System.nanoTime();
    while (System.nanoTime() - prevTime <= sleepTime) {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

```

The app start with the same resolution for both devices. Any idea about how to get the same speed?

# Answer
Stop using pixels and use virtual units. Remember that if you don't have `camera.unproject();` in your input processing code, then you have bad input processing code.
> 2 votes

# Answer
LibGdx is taking care of the FPS itself, there's no need to for you to intervene.

remove all the fixing methods, your delta time is now -

```
gdx.graphics.getDeltaTime()

```

use only it (send it to world.step())
> 1 votes

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


# Question
Title: How to Enable NVIDIA Ambient Occlusion in my Game
I have a DirectX11 based game, and I want to enable NVIDIA's built in Ambient Occlusion (that is shown in the NVIDIA control panel, but it grayed out for my application). Is that possible? Or do I need to be a big time developer and arrange something special with NVIDIA to get their ambient occlusion to work with my game?

Here is what happens when attempt to enable ambient occlusion in my application:

I've searched and found that sometimes you can override the "not supported" message through the use of an NVIDIA inpector tool, however it looks like the override is only for specific games as shown below:

So my conclusion is either NVIDIA has to enable it somehow, or my game must render in a very specific way, which NVIDIA can pick up on and insert its ambient occlusion calculations into my scene. Is there any documentation of how this works online, or has anyone gotten NVIDIA's ambient occlusion to work for an application they wrote?

# Answer
From my understanding and research on the topic, enabling ambient occlusion on the control panel does not make your NVidia card do some voodoo magic and apply AO to your scene. That's the way I read it from this page.

> All of the games built on Valve’s Source engine support AO when **enabled from the CP**

Instead it's an option that gets signaled into your application, for example AO is set to off, and you deal with that setting in your application. With the example you would disable AO.

It makes sense when your options are `On`, `Off` or `Application Controlled` where `Application Controlled` are just in-game settings.

---

So how could you acehive this with your appliction? You would need to use NVAPI.

There is some documentation here and an API reference here. The documentation actually shows you how to change the VSYNC global settings (p.8).

Unfortunately I could not get it working on a application basis. Although I did manage to get applications that exist in the program settings via `NvAPI_DRS_FindApplicationByName`, just remember to set `NVDRS_APPLICATION.version = NVDRS_APPLICATION_VER;` before you pass it to the function.

---

Upon more research I have found NVidia ShadowWorks, which looks like it might be promising.

Hope this points you in the right direction.
> 2 votes

# Answer
The best answer for this is at the Nvidia source: http://www.geforce.com/whats-new/guides/ambient-occlusion#1
> 0 votes

---
Tags: directx, directx11
---


# Question
Title: Issue with rotating particle effects with DrawUserPrimitves
I am creating a voxel-like game in XNA/Monogame. I am trying to create particle effect of which I create by making a list that is populated every frame. My issue is here: I am using a WorldMatrix to help rotate the particles, but I don't see how I can rotate them with a translating because each particle is different. Here is an example:

```
partEffect.CurrentTechnique = partEffect.Techniques[0];
        partEffect.Parameters["View"].SetValue(camera.viewMatrix);
        partEffect.Parameters["Projection"].SetValue(camera.projectionMatrix);
        Vector3 rotAxis = new Vector3(1,0,0);
        Vector3 rotAxis1 = new Vector3(0, 1, 0);

        rotAxis.Normalize();
        Matrix worldMatrix = Matrix.CreateTranslation(-20.0f / 3.0f, -10.0f / 3.0f, 0);// *Matrix.CreateFromAxisAngle(rotAxis1, camera.HORIZONTAL) * Matrix.CreateFromAxisAngle(rotAxis, camera.VERTICAL);// *Matrix.CreateFromAxisAngle(rotAxis1, camera.HORIZONTAL);//RotateToFace(vertices[0].Position, camera.Position, new Vector3(0, 1, 0));//Matrix.CreateBillboard(vertices[0].Position, camera.Position, new Vector3(0, 1, 0), new Vector3(0,0,0));//Matrix.CreateFromAxisAngle(rotAxis, angle);//Matrix.CreateTranslation(-20.0f / 3.0f, -10.0f / 3.0f, 0) * Matrix.CreateFromAxisAngle(rotAxis, angle);
        partEffect.Parameters["World"].SetValue(worldMatrix);

```

The next code that I call after that is the actual draw code, but my problem is here: How do I modify that translation when it seems to be static while each particle is different? Here is my draw effect:

```
foreach (EffectPass pass in partEffect.CurrentTechnique.Passes)
{
pass.Apply();
     GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration);
}

```

So as you can see, the Matrix.CreateTranslation is called before I run my actual draw code. I just don't see how I can modify that translation so it works for every particle instead of just the translation for the single particle. Any insight would be greatly appreciated.

# Answer
If you ask how rotate particles to camera you can find explanation here.

But if you want rotate particles around normal vector you must do it when you generate vertices. If you do it like in the toturial a privide tnen you can save information about offset of each vertex of plane in that vertex, For example without rotation vertex offset for left top lertex of plane should be (-0.5, -0.5), but if you rotate it clockwise at 45 degrees it become (0, -0.71), for 90 (0.5, -0.5) and so on. Also, for this method you can not use texture coords, and you must add you must create your own vertex declaration with additional field for vertex offsets.
> 1 votes

---
Tags: xna, monogame, graphic-effects
---


# Question
Title: How can I split my entity manager class into a gameworld class and gamerenderer class?
I currently have a libGDX game where I have an entity manager class which is called in the gamescreen. Instead, I would like to utilise it in a gameworld class and a gamerenderer class, but I cannot figure out how to split it up (if that makes sense). I want to do this so that I can manipulate my player class separately and not as a part of the entity manager. Previous attempts have failed because taking 'player' away meant that checkCollisions stopped working (hence why I want to use gameworld and gamerenderer classes instead). Does anyone have any ideas on how to achieve this?

Here is my entity manager class:

```
public class EntityManager {
    private final Array<Entity> entities = new Array<Entity>();
    private final Player player;

    public EntityManager(int amount) {
        player = new Player(new Vector2(110, 15), new Vector2(0, 35));
        for (int i = 0; i < amount; i++) {
            float x = MathUtils.random(0, ManicMeltdowns.WIDTH - TextureManager.DROPS.getWidth());
            float y = MathUtils.random(ManicMeltdowns.HEIGHT, ManicMeltdowns.HEIGHT * 3);
            float speed = 2;
            addEntity(new Drops(new Vector2 (x, y), new Vector2(0, -speed)));
        }
    }

    public void update() {
        for (Entity e : entities)
            e.update();
        player.update();
        checkCollisions();
    }

    public void render(SpriteBatch sb) {
        for (Entity e : entities)
            e.render(sb);
        player.render(sb);
    }

    private void checkCollisions() {
        for (Drops e : getDrops()) {
            if (e.getBounds().overlaps(player.rectangle)) {
                ScreenManager.setScreen(new GameOverScreen());
            }
        }
    }

    public void addEntity(Entity entity) {
        entities.add(entity);
    }

    private Array<Drops> getDrops() {
        Array<Drops> ret = new Array<Drops>();
        for (Entity e : entities)
            if (e instanceof Drops)
                ret.add((Drops)e);
        return ret;
    }
}

```

Thanks.

# Answer
> 1 votes
I'm no too sure of the overall design of your game, but I don't see why you would need GameWorld or GameRenderer classes since `Screen`s generally accomplish such tasks.

To separate the player and keep collision detection you can simply require the instance as an argument:

```
private void checkCollisions(Player player) {
    for (Drops e : getDrops()) {
        if (e.getBounds().overlaps(player.rectangle)) {
            ScreenManager.setScreen(new GameOverScreen());
        }
    }
}

```

---
Tags: java, libgdx
---


# Question
Title: OnCollisionEnter2D incorrect contact point?
I am trying to shoot a bullet (rigidbody2d, boxcollider2d) to another enemy object (rigidbody2d, kinematic, circlecollider2d). I want the collision point between these two. When they collide, i want a collision particle effect and from the contact point, i want to create 5 rock objects all moving in different directions. How should i achieve this? Problem is that, the contact point i get seems incorrect. Collision particle effect is created when collision happens but the rock objects are created in some other point close to the contact point but not the contact point. Also how to i move the rock objects in different directions after instantiating them?

my code:

```
void OnCollisionEnter2D(Collision2D coll)
{
    if (coll.gameObject.tag == "Enemy")
    {
        ContactPoint2D contact = coll.contacts[0];

        GameObject rock1 =  Instantiate (rock, contact.point, transform.rotation) as GameObject;
        rock1.rigidbody2D.velocity = transform.up * 20;
        GameObject rock2 =  Instantiate (rock, newPos, transform.rotation) as GameObject;
        rock2.rigidbody2D.velocity = transform.right * 20;
        Destroy(coll.gameObject);
        Destroy (gameObject);
        Instantiate (explosion, transform.position, Quaternion.identity);

    }
}

```

# Answer
> 1 votes
```
void OnCollisionEnter2D(Collision2D coll)
{
    if (coll.CompareTag("Enemy")) // more efficient
    {
        ContactPoint2D contact = coll.contacts[0];

        for(int i = 0; i < 5; ++i) // should probably be completely replaced with a particle system depending on your goals.
        {
           GameObject rock =  Instantiate (rock, contact.point, transform.rotation) as GameObject;
           rock.rigidbody2D.velocity = Random.insideUnitCircle * 20;
        }

        Instantiate (explosion, transform.position, Quaternion.identity);

        Destroy(coll.gameObject);
        Destroy (gameObject);
    }
}

```

If the contact point is incorrect then the issue is probably that your Enemy object is in a hierarchy and the contact point is in local space but your rocks are being created in world space. To fix this when you instantiate your rock you need to add the rock to the hierarchy or translate it so it matches the contact.point.

---
Tags: unity, collision-detection, rigid-body-dynamics
---


title: unity 5 how to get a shadowmap

text:
# Question
Title: unity 5 how to get a shadowmap
I'm writing a custom shader in unity 5 that requires a shadowmap (not just for drawing shadows but also for different computations involving scattering particles through fog). Does anybody know how to actually get the shadow map in unity rather than just using the fallback option? That is including the actual Z buffer not just the resulting 1's and 0's.

I could also use the depth buffer from the camera but that only appears to apply to camera used by the player rather than the second one I can add to replace the light (inside the light).

# Answer
In the Unity docs under shader references.

Shadow mapping macros

Declaring and sampling shadow maps can be very different depending on the platform, so Unity has several macros to help with that:

```
UNITY_DECLARE_SHADOWMAP(tex) - declares a shadowmap texture variable with name “tex”.
UNITY_SAMPLE_SHADOW(tex,uv) - samples shadowmap texture “tex” at given “uv” coordinate (XY components are texture location, Z component is depth to compare with). Returns single float value with the shadow term in 0..1 range.
UNITY_SAMPLE_SHADOW_PROJ(tex,uv) - similar to above, but does a projective shadowmap read. “uv” is a float4, all other components are divided by .w for doing the lookup.

```
> 5 votes

---
Tags: unity, shaders, shadows, depth-buffer, shadow-mapping
---


title: What's the scope of RPCs in unity?

text:
# Question
Title: What's the scope of RPCs in unity?
I can define several `RPCs` in unity and I can call them via the `networkView` component. But it seems that it gets the `RPC` called regardless where it is defined.

So I was wondering to know how do the scope of `RPC` works in Unity. Am I able to call whatever `RPC` in whatever script which share the same `networkView`? Or is there any other logic behind?

As a corollary: can I define a unique structured file gathering every `RPC` in my project?

# Answer
> 2 votes
Unity will invoke the RPC method on ALL methods with that name that appear in any of the game object's components.

Yes, you could do that, I personally wouldn't recommend it. It will add unneeded dependencies in your project, and pretty much destroys the point OOP.

Right now the RPC scope thing is really quite terrible. Imagine if you have an RPC method in a base class called A. Suppose classes B and C inherit from A. Now, if you attach scripts of both B and C to a single game object( not unrealistic ), RPC calls to methods in the base class simply won't work properly.

Fortunately, this seems to be getting fixed: https://www.youtube.com/watch?v=ywbdVTRe-aA

They seem to be sorting out the networking component of Unity. Hopefully we're not waiting too long.

---
Tags: unity, networking
---


title: Only 1 side is rendered

text:
# Question
Title: Only 1 side is rendered
I'm trying to get my .blend object into Unity but for some reason I see it differently in Unity than in Blender.

I was trying to solve the problem and someone said that I have to go to the edit mode, then mesh, then change the normals but that is not working for me.

Here is what I mean:

# Answer
`Edit-mode->ctrl-N` (make sure you have the entire mesh selected.)

What is happening is you have normals on one half of the front facing the wrong way so you're getting a backface culling on half of the object. The ctrl-N hotkey recalculates the normals to make them uniform across the surface. To edit a specific normal, you do:

`Edit-mode->N->scroll down to "Mesh Display" on the panel that appears on the right->Select on of the 3 options under "Normals"`

Then you can edit your normals by selecting a mesh-element and then doing `W->Flip-Normals`
> 2 votes

---
Tags: unity, blender, mesh
---


title: Kerning between glyphs using SDL2_ttf

text:
# Question
Title: Kerning between glyphs using SDL2_ttf
I'm loading a number of characters (using SDL2\_ttf) into a texture atlas to improve performance.

The glyphs can be separately rendered correctly, however, how can you find the kerning distance between two characters that will sit next to each other?

As a follow up, are there any other variables that impact font rendering?

# Answer
Documentation linked by akaltar has something to say about kerning support in SDL\_ttf: https://www.libsdl.org/projects/SDL\_ttf/docs/SDL\_ttf.html#IDX24

Most important for you is last sentence:

> There's currently no method to retrieve the kerning for a pair of characters from SDL\_ttf, However correct kerning will be applied when a string of text is rendered instead of individual glyphs.

It seems that only method would be to use FreeType directly. As there is no way to get `FT_Face` from SDL\_ttf context you would have to open font yourself and use `FT_Get_Index` and `FT_Get_Kerning` (http://www.freetype.org/freetype2/docs/reference/ft2-base\_interface.html).

Maybe it would not be that hard to add such functionality to SDL\_ttf and then push it upstream.

Problem is SDL\_ttf seems to not have separate user callable *shaping* phase - where placing glyphs is separate process to rendering them. It's just simpler API.
> 1 votes

# Answer
The current implementation from mercurial has this function in the headers:

```
int TTF_GetFontKerningSize(TTF_Font *font, Uint16 previous_ch, Uint16 ch);

```

And I believe this is exactly what you are looking for.
> 0 votes

---
Tags: rendering, sdl, fonts, sdl2
---


# Question
Title: Space invader barrier implementation algorithm
I've been struggling with implementing the space invader bullet to barriers. I wanted right now to blast a circle around, when the bullet hits the barrier and modifies the circle. As shown in the video, the algorithm looks wrong, http://youtu.be/VMBczCsP3J4 I have tried my best to debug it, but I've failed.

here is the algorithm:

```
// if there is intersection
    if (IntersectsWith((*it)->BoundingRect, barrierRect))
    {
        // subtract (*it) bullet position from barrrier's rect
        int normX = (*it)->Position.x - barrierRect.x;
        int normY = (*it)->Position.y - barrierRect.y;

        // barrier image pixels
        uint32* ptr = (uint32*)pixels;
        // height of the barrier
        int y = 31;

        for (int i = 0; i < 31; i++)
        {
            int pixelOffset = y + normX * 51;
            int color = ptr[pixelOffset];
            // look up the color if its not black, it should be green
            if (color != 0xFF000000)
            {
                // delete the bullet
                Bullet *bullet = *it;
                it = ship->Bullets->erase(it);
                delete bullet;
                ship->Canfire = true;
                isCollision = true;

                // blast a circle around that bullet hit position
                int radius = 9;
                for (int y = -radius; y <= radius; y++)
                {
                    for (int x = -radius; x <= radius; x++)
                    {
                        if (x*x + y*y <= radius*radius)
                        {
                            int j = x + normX;
                            int i = y + normY;
                            int pixelOffset = j + i * 51;
                            ptr[pixelOffset] = 0xff000000;
                        }
                    }
                }
                break;
            }
            // go up
            y--;
        }

```

# Answer
> 0 votes
Your `pixelOffset` calculations are inconsistent...

```
int pixelOffset = y + normX * 51;

```

is different than...

```
int j = x + normX;
int i = y + normY;
int pixelOffset = j + i * 51;

```

One uses x * 51 + y and the other uses y * 51 + x.

**EDIT** You are also reusing variable `i` and `y`.
I think you want your blast circle to be based on your outer `y` value in addition to the inner. Notice `y + yy + normY` below.

```
            // blast a circle around that bullet hit position
            int radius = 9;
            for (int yy = -radius; yy <= radius; yy++)
            {
                for (int xx = -radius; xx <= radius; xx++)
                {
                    if (xx*xx + yy*yy <= radius*radius)
                    {
                        int jj = xx + normX;
                        int ii = y + yy + normY;
                        int pixelOffset = jj + ii * 51;
                        ptr[pixelOffset] = 0xff000000;
                    }
                }
            }

```

# Answer
> 1 votes
Looks to me that your intersection code is not returning the correct position of impact. This could due that that when the game checks whether the bullet collide with the object, the bullet is already inside the barrier. You need to modify the intersection code to return the exact moment when the bullet hits the barrier.

---
Tags: c++, 2d, algorithm, game-mechanics
---


# Question
Title: Using Appendbuffers in unity for terrain generation
Like many others I figured I would try and make the most of the monster processing power of the GPU but I'm having trouble getting the basics in place.

CPU code:

```
using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{
   public ComputeShader Generator;
   public MeshTopology Topology;

   void OnEnable()
   {
      var computedMeshPoints = ComputeMesh();
      CreateMeshFrom(computedMeshPoints);
   }

   private Vector3[] ComputeMesh()
   {
      var size = (32*32) * 4; // 4 points added for each x,z pos
      var buffer = new ComputeBuffer(size, 12, ComputeBufferType.Append);
      Generator.SetBuffer(0, "vertexBuffer", buffer);
      Generator.Dispatch(0, 1, 1, 1);
      var results = new Vector3[size];
      buffer.GetData(results);
      buffer.Dispose();
      return results;
   }

   private void CreateMeshFrom(Vector3[] generatedPoints)
   {
      var filter = GetComponent<MeshFilter>();
      var renderer = GetComponent<MeshRenderer>();

      if (generatedPoints.Length > 0)
      {
         var mesh = new Mesh { vertices = generatedPoints };
         var colors = new Color[generatedPoints.Length];
         var indices = new int[generatedPoints.Length];

         //TODO: build this different based on topology of the mesh being generated
         for (int i = 0; i < indices.Length; i++)
         {
            indices[i] = i;
            colors[i] = Color.blue;
         }

         mesh.SetIndices(indices, Topology, 0);
         mesh.colors = colors;

         mesh.RecalculateNormals();
         mesh.Optimize();
         mesh.RecalculateBounds();
         filter.sharedMesh = mesh;
      }
      else
      {
         filter.sharedMesh = null;
      }
   }
}

```

GPU code:

```
#pragma kernel Generate

AppendStructuredBuffer<float3> vertexBuffer : register(u0);

void genVertsAt(uint2 xzPos)
{
   //TODO: put some height generation code here.
   //      could even run marching cubes / dual contouring code.

   float3 corner1 = float3( xzPos[0], 0, xzPos[1] );
   float3 corner2 = float3( xzPos[0] + 1, 0, xzPos[1] );
   float3 corner3 = float3( xzPos[0], 0, xzPos[1] + 1);
   float3 corner4 = float3( xzPos[0] + 1, 0, xzPos[1] + 1 );

   vertexBuffer.Append(corner1);
   vertexBuffer.Append(corner2);
   vertexBuffer.Append(corner3);
   vertexBuffer.Append(corner4);
}

[numthreads(32, 1, 32)]
void Generate (uint3 threadId : SV_GroupThreadID, uint3 groupId : SV_GroupID)
{
   uint2 currentXZ = unint2( groupId.x * 32 + threadId.x, groupId.z * 32 + threadId.z);
   genVertsAt(currentXZ);
}

```

Can anyone explain why when I call "buffer.GetData(results);" on the CPU after the compute dispatch call my buffer is full of Vector3(0,0,0), I'm not expecting any y values yet but I would expect a bunch of thread indexes in the x,z values for the Vector3 array.

I'm not getting any errors in any of this code which suggests it's correct syntax-wise but maybe the issue is a logical bug.

Also: Yes, I know I'm generating 4,000 Vector3's and then basically round tripping them. However, the purpose of this code is purely to learn how round tripping works between CPU and GPU in Unity.

# Answer
Have you tried checking the counter in the append buffer, to see if ANYTHING is being appended?

```
ComputeBuffer argBuffer = new ComputeBuffer(4, sizeof(int), ComputeBufferType.DrawIndirect);
int[] args = new int[]{ 0, 1, 0, 0 };
argBuffer.SetData(args);

ComputeBuffer.CopyCount(buffer, argBuffer, 0);
argBuffer.GetData(args);

```

Then argBuffer\[0\] should be the total number of items appended to your first buffer. This blog is the only resource I've yet found:

http://scrawkblog.com/2014/08/14/directcompute-tutorial-for-unity-append-buffers/

A question, in the line:

```
AppendStructuredBuffer<float3> vertexBuffer : register(u0);

```

What does the register(u0) mean? I've been having weird results using append buffers, but instead of everything being empty, I just get strange output every once in a while. I think it's an initialization/memory allocation problem, but I can't sniff it out.
> 1 votes

# Answer
The compute shader never gets executed as you're nullifying the dispatch.

Try `Generator.Dispatch(0, 1, 1, 1);`
> 0 votes

---
Tags: unity, shaders, hlsl, vertex-buffer
---


title: Designing AI/NPC Task System

text:
# Question
Title: Designing AI/NPC Task System
I am designing a game in Unity which has NPCs (Non-player controllers). I have worked out the path-finding but I need some help with how to implement tasks. I need the task system to be flexible and allow me to easily add new tasks. I also want to be able to have a task trigger another task.

Example for turning light on:

* When mouse clicked on light switch
* Wait for available/idle NPC
* NPC walks to light switch (Using a walkToPostion(pos) task)
* Light turns on
* NPC is set to available/idle and can perform another task

Another example could be emptying the trash can:

* When trash can is full
* Wait for an available NPC
* NPC walks to trash can (Using a walkToPostion(pos) task)
* Trash can is set to empty
* NPC takes garbage bag outside (Using a walkToPostion(pos) task)
* NPC walks back into house/given position. (Using a walkToPostion(pos) task)
* NPC waits to be given next task.

I haven't done a lot with AI before so some hits on how I could go about implements this would be very helpful.

EDIT: One thing I specifically need help with is performing a task inside a task. How do I pause the TurnOnLight task while the player is doing to WalkToPos task?

# Answer
> 5 votes
A design pattern I've enjoyed using has two types of things: task management and task execution. Task management asks the question "What should I be doing right now?" And task execution asks, "How do I complete the current task?"

# Task Managers

The job of the task manager is to constantly look at the AI's internal state (read-only) to determine whether new tasks should be assigned. Tasks have priorities, and are placed on a Priority Queue when assigned. Tasks are also unique, so that an agent can't be assigned exactly the same task twice.

For instance, the Task Manager could constantly be checking to see if the agent has sensed any new enemies that must be attacked. If enemies are sensed, it adds high-priority DestroyThreat tasks to the task queue.

When the agent is done with the current task, it pops another one off the task queue. Task managers can also pre-empt the current task by putting it back on the queue if an extremely high priority task overrides the current task.

# Task Executors

Your agent will have several actions which are merely functions, bits of behavior tree, or states in a state machine. Every action can either fail, or succeed. These are implemented inside the AI agent itself. They should be atomic (like "play animation" or "attack entity").

The task executor will simply tell the AI agent what actions to take given a current task. It does not need to directly know about the agent's state, but only the return values of the actions the agent takes. The executor can either fail the task, or succeed, based on whether the current action fails or succeeds. If the task fails, it is either put back on the task queue or is destroyed, depending on the desired behavior.

# Answer
> 3 votes
The best way I can think of to do this is to have an empty object with a TaskController script. Assuming the NPCs have their own scripts, and you can call a function in their script to have them handle a task, your logic would flow like:

1. Player clicks on light switch
2. Light switch script calls CreateTask(TaskName, Index) on your TaskController empty's script, where TaskName = "TurnOnLight" and Index = 1 (light switch # 1 in your scene, if it has multiple switches)
3. TaskController creates a new task (likely a class object with parameters like TaskIndex, TaskName, TargetIndex, Assignee, and Completed)
4. TaskController finds the nearest Idle NPC and sends the task to them via function, then adds them to the Assignee field and sets Completed to false. (This also allows idle NPCs to periodically check the TaskController for unassigned, incomplete tasks)
5. NPC can now execute its WalkTo function and head for the light switch. TaskController will know not to assign the task to someone else because its Assignee slot is not blank.
6. When the NPC reaches its destination, it can re-check with the TaskController to make sure its task is still not Completed, then perform the task (flip on light if off else flip off).
7. Once the NPC performs the task, it can tell the TaskController to mark the task as Completed and set itself to idle and wander off for a beer.

Let me know if you need more detail.

---
Tags: unity, game-design, ai, npc
---