Friday, September 19, 2014

What is Vector2D, Vector2D magnitude, Vector2d.normalized? Learn all about Vectors and their normalized vectors, dot product and other necessary stuff.

Hi,

Today I will explain a little bit of Vectors and their properties. We have to learn a few things about Vectors, both in 2D and 3D because we do need them in Unity. By the way, I will give Vector2D functions and try to explain using them but these rules and functions also apply to Vector3 counterparts. Just replace Vector2D with "Vector3D" , the rest is all the same.

tip: learn this basic vector knowledge well, these will help you in the long run of Unity and game making business.

Lets summarry the main parts:
1) Vector2d logic and What Vector2.normalized and Vector2d magnitude value means?
2) Dot vector product.
3) How to and Why to compare them?

I will try to explain them step by step.


First of all, what is a normalized Vector means? 
By saying normalized vector, we are talking about a vector which has a length of 1 unit. It makes a vector bigger if it has a length smaller than 1 or makes a vector smaller if it's  original length bigger than 1.

Lets say we have a Vector2D named A, which is 2 points in x and 3 points in y, like this:
Vector2D A = new Vector2D(2,3);

if we get its normalized vector, we will use "normalized" function of Vector2D. Like this:
Vector2D B = A.normalized;

Now we get a B vector, which is just a smaller copy of the original A vector. BOTH vectors have the SAME DIRECTION! this is important to know. But normalized one is just a smaller copt of the original.

Because a normalized vector has a magnitude of 1. Always. Period.

Btw, is you dont know the term "magnitede" dont worry. Magnitude is just a fancy word for "length" in mathematics. So when you hear the word "magnitude" of a vector, just think it's LENGTH.

Lets be more clear, a normalized Vector has a length of 1, and has the same direction of the original vector.

here is a picture of a vector (shown as original vector) and it's normalized vector:



Lastly, some well-known normalized Vectors:

Vector2D.right : Vector2(1, 0) : a normalized vector to the right.
Vector2D.up : Vector2(0, 1) : a normalized vector to the up.

here is an imaginary images of  static normalized Vectors.



Now to the second step...

2) Vector DOT product: 

Dont tnik too much about this term. It just compares (usually) 2 normalized vectors. This is that dot product goodness is all about. You give 2 normalized (which means 2 vectors with a length of 1) to the dot function of Vector2D, and you get a comparizon of those 2 vectors. Since they do have the same lenght (they both have 1 unit lenght remember?) the only think that they can be compared to is their direction. When you Vector.Dot 2 vectors, you get a float number! So what does that float number symbolize, how can a comparison function gives you a float number and expects you to get that comparison from that number?

Well, The main trick here is how to read that float number.

First of all, dot function always gives a float number between -1 and +1. What ever you do, whichever 2 vectors you give, you will always get a  number between -1 and 1. So here comes the magic:

a) if 2 vectors  both do have exactly the same direction, then you get number +1;
b) if 2 vectors  have completely opposite directions, , then you get number -1;
c) if 2 vectors are perpendicular, then you get number 0.
d) you get different number  between +1 and -1 for other cases which gives us a clue of their position to each other.

are you getting the point?

You can compare two vectors directions by looking at Vector2D.Dot function, which the term comes "getting a dot product of two vectors".

An example image of Dot Product Results and different two vectors:




So you learned what s a magnitude, how to get a vectors normalized value, and how to compare two normalized vectors using Vector's Dot method (getting dot product and examining the float number) now you can do some neat stuff with this knowledge, like handlind and managing  SLIDE controllers.

On my next article, I will explain how can you capture slide gestures, tap and click on mobile screen and how to optimize slide and how to get which way user slides from and slides through.. Wont last long, so hope to see you soon.






Tuesday, April 22, 2014

Android Signing - Just before you upload to Google Store you need a keytool - sign your apk file

For development you dont need but for for publishing (i.e. Android Market) you have to sign in your  apk file.

1) Locate the Publishing Settings under PlayerSettings
2) Create a new keystore by selecting a keystore name and password (confirm the password)
3) Select "Create a new key" under Key Alias
4) A new window opens; enter the necessary information.
5) Select the newly created key.
6) Build ( & Run); your app is now signed.

Dont forget your password. That is important. If you ever forget your password you cant upload your apk file later! Always remember the passwords; they are not stored with the project (for security reasons).


Big List of Indie Game Earnings - Success stories.

Found a good webpage, which has lots of indie gamer earnings. A real good list of success stories. Be sure to read on http://www.pixelprospector.com/the-big-list-of-game-revenue-sales.


Here are the links, (I wanted to archieve this if orijinal post will somehow dissapear in the future)

---


Wednesday, April 9, 2014

Unity3d - MiniJSON - Facebook SDK for Unity

MiniJSON knowledge

1) Anything that is wrapped in curly brackets {}  converts to "Dictionary<string, object>"
2) all the keys are sthe strings on the left side of the colon (:)
3) values are on the right side of the colon (:)
4) anything wrapped in square brackets [] convert to a List<object>
5) all values converts to System.String which then be converted to whatever type you want with the system string convert functions.

Some examples to serialize / deserialize facebook sdk output in Unity3D:


void OnLoggedIn()                                                                        
{                                                                                        
//Debug.Log("Logged in. ID: " + FB.UserId);
// Reqest player info and profile picture                                                                        
FB.API("/me?fields=id,first_name,last_name,picture,friends.limit(10).fields(first_name,id,last_name,picture)", Facebook.HttpMethod.GET, APICallback);
//LoadPicture(GetPictureURL("me", 128, 128),MyPictureCallback);
}

void APICallback(FBResult result)                                                                                            
{                                                                                                                            
Debug.Log("APICallback");                                                                                              
if (result.Error != null)                                                                                                
{                                                                                                                        
Debug.LogError(result.Error);                                                                                          
return;                                                                                                              
}              

myFacebookProfile = DeserializeJSONProfile(result.Text);
// Debug.Log("+++++++++++ facebook profile :" +
//          "firname: " + myFacebookProfile.first_name +
//          ", lastname:" + myFacebookProfile.last_name +
//          ",id: " + myFacebookProfile.id +
//          "picture: " + myFacebookProfile.profile_image_url+
//          ",is_silhoutte" + myFacebookProfile.Profile_image_is_silhoutte);


myFacebookFriends =  DeserializeJSONFriends(result.Text);
int i = 0;
foreach (FacebookProfile fd in myFacebookFriends) {
i++;
Debug.Log("+++++++++++" + i +") nolufriend:" +
         "firname: " + fd.first_name +
         ", lastname:" + fd.last_name +
         ",id: " + fd.id +
         "picture: " + fd.profile_image_url+
         ",is_silhoutte" + fd.Profile_image_is_silhoutte);
}
}


public FacebookProfile DeserializeJSONProfile(string response)
{
FacebookProfile profile = new FacebookProfile();
Dictionary<string, object> responseObject = Json.Deserialize(response) as Dictionary<string, object>;
object nameH;
Dictionary<string,object> tempDictionary;

if (responseObject.TryGetValue("first_name", out nameH))
{
profile.first_name = (string)nameH;
}
if (responseObject.TryGetValue("last_name", out nameH))
{
profile.last_name = (string)nameH;
}
if (responseObject.TryGetValue ("id", out nameH)) {
profile.id = (string)nameH;
}

if (responseObject.TryGetValue ("picture", out nameH)) {
tempDictionary = (Dictionary<string,object>) nameH;
if (tempDictionary.TryGetValue ("data", out nameH)) {
tempDictionary = (Dictionary<string,object>) nameH;
profile.profile_image_url = (string) tempDictionary["url"];
profile.Profile_image_is_silhoutte = (bool) tempDictionary["is_silhouette"];
//resim bilgisi gönderilmiş ise, resmi download edelim arka planda:
if(profile.Profile_image_is_silhoutte == false) {
StartCoroutine(LoadProfilePictureEnumerator(profile));
}
}

//Dictionary<string,object> friendPictureData = (Dictionary<string,object>)((Dictionary<string,object>)responseObject["picture"])["data"];
//profile.profile_image_url = (string) friendPictureData["url"];
//profile.Profile_image_is_silhoutte = (bool) friendPictureData["is_silhouette"];
}

return profile;
}

public List<FacebookProfile> DeserializeJSONFriends(string response)
{
List<FacebookProfile> facebookFriends = new List<FacebookProfile>();
var responseObject = Json.Deserialize(response) as Dictionary<string, object>;
object friendsH;
Dictionary<string,object> tempDictionary;

bool runned_once = false;
do {
if (!responseObject.TryGetValue("friends", out friendsH))
{
break;
}

List<object> friendsDataContainer = (List<object>)(((Dictionary<string, object>)friendsH)["data"]);
foreach (Dictionary<string,object> friendData in friendsDataContainer) {
FacebookProfile friend = new FacebookProfile();

if (friendData.TryGetValue("first_name", out friendsH))
{
friend.first_name = (string)friendsH;
}
if (friendData.TryGetValue("last_name", out friendsH))
{
friend.last_name = (string)friendsH;
}
if (friendData.TryGetValue ("id", out friendsH)) {
friend.id = (string)friendsH;
}


//resimleri bulmak için bir tur daha aşagı inecegiz

if (friendData.TryGetValue ("picture", out friendsH)) {
tempDictionary = (Dictionary<string,object>) friendsH;
if (tempDictionary.TryGetValue ("data", out friendsH)) {
tempDictionary = (Dictionary<string,object>) friendsH;
friend.profile_image_url = (string) tempDictionary["url"];
friend.Profile_image_is_silhoutte = (bool) tempDictionary["is_silhouette"];
//resim bilgisi gönderilmiş ise, resmi download edelim arka planda:
if(friend.Profile_image_is_silhoutte == false) {
StartCoroutine(LoadProfilePictureEnumerator(friend));
}
}

//Dictionary<string,object> friendPictureData = (Dictionary<string,object>)((Dictionary<string,object>)responseObject["picture"])["data"];
//profile.profile_image_url = (string) friendPictureData["url"];
//profile.Profile_image_is_silhoutte = (bool) friendPictureData["is_silhouette"];
}


//
// //var friendPictureDataContainer = friendData ["picture"] as Dictionary<string,object>;
// //var friendPictureData = friendPictureDataContainer["data"] as Dictionary<string,object>;
// Dictionary<string,object> friendPictureData = (Dictionary<string,object>)((Dictionary<string,object>)friendData["picture"])["data"];
//
// friend.profile_image_url = (string) friendPictureData["url"];
// friend.Profile_image_is_silhoutte = (bool) friendPictureData["is_silhouette"];
//
// //profile resmini arka planda download et ve profile classına yükle
// StartCoroutine(LoadProfilePictureEnumerator(friend));

//friend bilgilerini listeye ekle
facebookFriends.Add(friend);
}
runned_once = true;
} while (!runned_once);
return facebookFriends;
}


How to invite friends using Facebook SDK for Unity3D

Yıu can call this code for inviting your facebook friends using Unity3D facebook SDK.


if(FB.IsLoggedIn)
{
    FB.AppRequest(
        message: "Come and Play This Game!",
        title: "My Game Invitation For Facebook Friend",
        callback: InviteCallback
    );
}

// ...

void InviteCallback(FBResult response)
{
Debug.Log("facebook invitation from Unity3D sent");
}



if(FB.IsLoggedIn)
{
    FB.AppRequest(
        message: "Come and Play This Game!",
        title: "My Game Invitation For Facebook Friend",
        callback: InviteCallback
    );
}

// ...

void InviteCallback(FBResult response)
{
Debug.Log("facebook invitation from Unity3D sent");
}



If your app is in sandbox mode, people won't get notified when the request is sent. So change your facebook application settings to "public"  in https://developers.facebook.com/apps page, goto "Status & Review" tab on le menu on the left. On the right you will see "Do you want to make this app and all its live features available to the general public?" question. Set its value to "YES" . If you cant modify YES/NO section then you have to give your application a contact email  on "Settings" tab on left menu.



Look for the request in https://www.facebook.com/appcenter/requests as the recipient and see if the request shows up there.



How to check facebok invitations: 

If you want you can also check invitation from FBResult response object, maybe even call how many people does this invitation is sent. An example code:

private void InviteCallback(FBResult result)
    {
        if (result != null)
        {
            var responseObject = Json.Deserialize(result.Text) as Dictionary<string, object>;
            IEnumerable<object> objectArray = (IEnumerable<object>)responseObject["to"];

            if (objectArray.Count() >= 3)
            {
                // 3 facebook invitations send. Give user a free item or bonus etc.
            }
        }
    }


Btw, facebook also gives us nice shiny login buttons, which can be downloaded from this address: https://developers.facebook.com/docs/facebook-login/checklist .






Tuesday, April 8, 2014

How to download content or picture image in the background using WWW class?

 Unity3D has a utility module for retrieving the contents of URLs named as WWW class. WWW class can also download a picture image,  so that you can assign that picture on the internet as a Texture in your Unity3D project.



Remember, WWW class is a Coroutine and runs background.

I can recommend two different ways of implementing background downloading in Unity3D.

First way; You can just yield it until it is completed. For example:

void IEnumerator Start() {
    WWW www = new WWW( url );
    yield return www;
   Texture2D myPicture = www.texture;  //this is how you download and image from web in untiy3d.
}


Second Way;  you can inspect the isDone property of WWW class to see if the download has completed or not. Here is an example of using the isDone and progress properties:

float progress = 0.0f;
void IEnumerator Start() {
    WWW myW = new WWW( url );
    while( !myW.isDone )
    {
        progress = myW.progress;
        yield return null;
    }
    progress = 1.0f;
}

Tip: You can create a progress bar with that progress property in OnGUI function.



Thursday, April 3, 2014

Unity3D and facebook SDK login problem for android devices

So you created you Unity3D game, integrated with Facebook's shining plugin. But still you are not able to login right? Infact nothing happens when you click that login button.

here is the problem: key_store hash!

I know you installed openssl and put your key on your facebook page.

well the thing is your key_hash is not valid.

When you debug your application with adb logcat, you can see a row like this:

"W/fb4a(:<default>):BlueServiceQueue(19773): com.facebook.http.protocol.ApiException: Key hash ******* does not match any stored key hashes."

**** = a key hash which I masked for privacy reasons.

well use that key_hash on your facebook app page.

go https://developers.facebook.com/apps  and select your aplication, choose "Settings" from the menu on the left and write that key hash which you see on the adb logcat log on facebooks key hashes part.  Save and update facebook.

that is it.

If you dont know how to use adb log cat, read my article on this url:

---

Here is a quick how to use adb :

1) goto your sdk installation directory, (adt\sdk\platform-tools) and run this command:
adb logcat  > mylog.txt

this command will dump all logs to mylog.txt file. open that file and search for key hash keyword on the log.  To Search adn solve your login problem ,  do these:

i) open mylog.txt in your favourite text editor.
ii) search this word: ApiException
you will find some rows like this: 

W/fb4a(:<default>):BlueServiceQueue(26232): com.facebook.http.protocol.ApiException: [code] 404 [message]: Key hash yd13SdjudjDdwdwedWsdddcwVJW  does not match any stored key hashes. [extra]: null
( there you will find your real key hash: yd13SdjudjDdwdwedWsdddcwVJW) 

iii) put  an extra = sign at the end and key hash become like this: yd13SdjudjDdwdwedWsdddcwVJW=

iv) copy paste this keyhash into your facebook developer page. all your facebook sdk login problems will be gone. 
 ----

These steps also valid for macbook - macos unity - fcebook login sdk problems. 


There you will find your real key hash. Use this key hash on facebook key hashes form. The one unity creates is false.


------

btw Isearched a lot on internet and find these solutions below. But I did not try any of them. so you can also try these ones:

1) Some people say openssl which you install really matters and recommends to install a spesific version. Maybe with that openssl unity panel will give you the real key hash, I did not try try that.

2) Also create two key hashes one for debug one for release with these commands:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

keytool -exportcert -alias yourappreleasekeyalias -keystore ~/.your/path/release.keystore | openssl sha1 -binary | openssl base64

some urls you may invetigate further:
http://stackoverflow.com/questions/13894006/android-facebook-sdk-3-0-gives-remote-app-id-does-not-match-stored-id-while-lo/16059786#16059786

http://answers.unity3d.com/questions/576088/facebook-sdk-simple-login.html

http://stackoverflow.com/questions/13894006/android-facebook-sdk-3-0-gives-remote-app-id-does-not-match-stored-id-while-lo

http://stackoverflow.com/questions/19051361/facebook-unity-sdk-on-android-login-fails-when-fb-app-installed/19091114#19091114

http://stackoverflow.com/tags/facebook-unity-sdk/hot

http://answers.unity3d.com/questions/609810/using-facebook-api-with-android-says-login-is-canc.html


Wednesday, April 2, 2014

how to debug unity3d with adb logcat

There is something called the logcat, which is a combined message pipe from all applications. To read it you first need to locate the adb tool that comes with the Android SDK. Depending on which version you have of the SDK the adb is located either under<sdk>/tools or<sdk>/platform-tools.

Simply start it like this:

$ adb logcat

and it will start printing out everything that is going on on the device. To limit it to only show the output from inside Unity, you can try this:

$ adb logcat -s Unity

or, to get a little bit more info about what's going on:

$ adb logcat -s Unity ActivityManager PackageManager dalvikvm DEBUG

If you wish to report a bug or otherwise 'quote' the logcat, you can dump the complete logcat to a file like this:

$ adb logcat -d > logcat.txt

unity3d and facebook sdk problem - Error building Player: Win32Exception: ApplicationName='C:\Program Files (x86)\Java\jre7\bin\javac.exe',

If you are going to use facebook SDK for unity3d, then you will get these problems.

If you come across with this error: 
Error building Player: Win32Exception: ApplicationName='C:\Program Files (x86)\Java\jre7\bin\javac.exe',

then you only have Java JRE which does not come with javac.exe. You must install JAVA JDK from java website . Also be sure to read about  PATH Environment Variable (Optional) on java documentation page.  

You need JAVA JDK ! Not JRE !



here is the way to set environment table for java path: 
C:\> "C:\Program Files\Java\jdk1.7.0\bin\javac" MyClass.java
It is useful to set the PATH variable permanently so it will persist after rebooting.
To set the PATH variable permanently, add the full path of the jdk1.7.0\bin directory to the PATH variable. Typically, this full path looks something like C:\Program Files\Java\jdk1.7.0\bin. Set the PATH variable as follows on Microsoft Windows:
  1. Click Start, then Control Panel, then System.
  2. Click Advanced, then Environment Variables.
  3. Add the location of the bin folder of the JDK installation for the PATH variable in System Variables. The following is a typical value for the PATH variable:
    C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Java\jdk1.7.0\bin
Note:
  • The PATH environment variable is a series of directories separated by semicolons (;) and is not case-sensitive. Microsoft Windows looks for programs in the PATH directories in order, from left to right.
  • You should only have one bin directory for a JDK in the path at a time. Those following the first instance are ignored.
  • If you are not sure where to add the path, add it to the right of the value of the PATH variable.
  • The new path takes effect in each new command window you open after setting the PATH variable.


also you may have to set JAVA_HOME to the directory on your machine that does have JDK (and javac.exe) installed.


here is a step by step how to change JAVA_HOME directory:

Set the JAVA_HOME Variable
Once you have the JDK installation path:
  1. Right-click the My Computer icon on
  2. your desktop and select Properties.
  3. Click the Advanced tab. Click the
  4. Environment Variables button. Under System Variables, click New.
  5. Enter the variable name as JAVA_HOME.
  6. Enter the variable value as the installation path for the Java Development Kit.
  7. Click OK.
  8. Click Apply Changes.
You might need to restart windows.
NOTE: You have to put the path to the jdk without /bin in the end.
For example:  C:\Java\jdk1.6.0_44 , NOT C:\Java\jdk1.6.0_44\bin.

You have to restart Unity3D so that unity can read the new java home path. After this you can build your unity3d game with facebook sdk without any problems.



Btw, if you need openssl for windows to create keystore for facebook sdk for unity3d, you must first download openssl and extrac its bin folder content to C:\Program Files\Java\jdk1.8.0\bin (or whereever you java install dir is) then add C:\Program Files\Java\jdk1.8.0\bin to enviroment path.

and to create keystore: 

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | penssl.exe sha1 -binary | openssl.exe base64



and the SECOND common problem is this error: 
... your android debug keystore file is missing ...

This second problem is  EASY  to fix. 
This happens when your your Unity project is on another drive than C: drive. Anyway this is not a problem. You need to fix a c# script in facebook directory in your unity project panel. Locate Facebook>Android>FacebookAndroidUtil cd file.  Open file. Find this row: 
System.Environment.GetEnvironmentVariable("HOMEPATH") + @"\.android\debug.keystore" : 
and change it with this one: 
System.Environment.GetEnvironmentVariable("HOMEDRIVE") + System.Environment.GetEnvironmentVariable("HOMEPATH") + @"\.android\debug.keystore" :

save the file. and restart unity3d. you will see that your problems will go away :) 

Monday, March 31, 2014

unity3d - hit all objects on the screen or hit only one object on the screen click

Here is an example code:


//hit only 1 object
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitScreenObject;
if(Physics.Raycast(ray,out hitScreenObject))
{
if(Input.GetMouseButtonDown(0))
{
//isHit = false;
Destroy(hitScreenObject.collider.gameObject);
}
}

//hit all objects at the same time
RaycastHit2D[] hits;
//hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F);
//Ray2D ray = Camera.main.ScreenPointToRay(Input.mousePosition, Vector2.zero);
                //Physics2D.raycastsHitTriggers = true;
               
                hits = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
               
           


Wednesday, March 26, 2014

Unity3d Preloading Scenes with allowSceneActivation = false working (Loading scene in background)

Loading Scene in Background without switching the level immediately.


Read below to find a working (and tested)  way of loading scene in background in Unity3d. Also it wont  switch next level immediately.

If you are trying to preload a new scene, you have to use Application.LoadLevelAsync("sceneName"); method. I have managed to use this function with allowSceneActivation=false. When you set allowSceneActivation to false, you will probably sett that Unity Editor hangs. This is why you must use a different approach to achieve preloading.

IF allowSceneActivation locks up  Unity Editor  try this script:

IEnumerator LevelLoaderProcess() {
AsyncOperation status = Application.LoadLevelAsync("gameScreen");
status.allowSceneActivation = false;

// Wait until done and collect progress as we go.

//while( !status.isDone )
//{
loadProgress = status.progress;
if( loadProgress >= 0.9f )
{
Debug.Log("almost done");
// Almost done.
//break;
}
yield return null;
//}

while (!doLoadNextFrame) {
Debug.Log("still waiting");
                       //You can do whatever you want here...  
yield return new WaitForSeconds(1.0f);
}
// Allow new scene to start.
status.allowSceneActivation = true;
//yield return status;
}

You see that 0.9f if condition? Well that is the trick. When you set status.allowSceneActivation to false, unity3d stops loading target scene as soon as it loads  %90 of scenes content. And starts to wait for that 10 percent to load the next scene.  To load that 10% data, Unity3d will be waiting for status.allowSceneActivation = true; command.

Script I share above handles this issue.


Another thing to notice. DO NOT put your StartCoroutine command in AWAKE function. This also makes  unity crash, your editor crashes which makes it unresponsive. This is a Untiy3d bug I believe.  You can put a gui button in your  OnGUI  method to start your coroutines. Like this:

void OnGUI()  {
if (GUI.Button (new Rect (10, 10, 50, 50), "sirinlike")) {
StartCoroutine (LevelLoaderProcess());
}
}





Tuesday, March 25, 2014

fonts for your unity3d games

Font sites:
1) da font: http://www.dafont.com/
Both free and paid fonts. A few cool ones:

+ Laurus Nobilis  : Roman senate games.


----

and if you are wondering how to display your fonts, text, etc.. be sure to read : http://johnstejskal.com/blog/unity3d-how-to-make-a-2d-gui-hud-interface-to-display-scorelives


---

changing the sprites:
http://forum.unity3d.com/threads/212619-Mini-tutorial-on-changing-sprite-on-runtime

unity3d - mechanim animator tutorial videos

1) a quick usage: http://www.youtube.com/watch?v=HXN9lq9syTE

Monday, March 24, 2014

instantiate object at mouse position - change mouse position to world position.

If you are trying to instantiate a gameobject when player clicks on surface, you have to find the world point of the tabbed place. Then you can instantiate your object. 

You can get hit.point to find where the object is hit. If you are trying to make a shooting game. This will give you the world position. 

Or you can use mouse position and since mosue position is screen coordinates you change it into world position. 

Input.mousePosition is in screen coordinates (in pixels)

To get a position in world coordinates you need to use Camera.main.ScreenToWorldPoint(Input.mousePosition). 

Input.mousePosition is also a 2 dimensional position (because your screen is flat). To get a correct and meaningful world position you will also have to specify a z coordinate to describe how far in front of the camera the world point should be. So if you have a camera looking straight down onto a plane and the camera has a distance of 10 to the plane you would set the z coordinate to 10 to instantiate something on that plane.

here is an example code which gives the world point of Input.mousePosition. 

Vector3 myPos = Input.mousePosition;

myPos = Camera.main.ScreenToWorldPoint(myPos);

myPos.z = 10f;   //you have to modify z coordinate since it will always give you the camera's z position. 


here is an other code which I find on http://answers.unity3d.com/questions/32807/instantiate-object-at-mouse-position.html page. 


  1. Vector3 mousePos=new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f);
  2.  
  3. if(Input.GetMouseButtonDown(0)) {
  4. Vector3 wordPos;
  5. Ray ray=Camera.main.ScreenPointToRay(mousePos);
  6. RaycastHit hit;
  7. if(Physics.Raycast(ray,out hit,1000f)) {
  8. wordPos=hit.point;
  9. } else {
  10. wordPos=Camera.main.ScreenToWorldPoint(mousePos);
  11. }
  12. Instantiate(thePrefab,wordPos,Quaternion.identity);
  13. //or for tandom rotarion use Quaternion.LookRotation(Random.insideUnitSphere)
  14. }


hope this helps.

useful links:

+ http://forum.unity3d.com/threads/50321-2D-screen-coordinates-to-3d-world-coordinates


Saturday, March 15, 2014

Rigidbody - collider - isKinematic - isTrigger in nutshell

Rigidbody : allows a gameobject to be effected by forces like gravity or movement. collider: it is a must to detect collisions. If you are after object collisions then both two objects must have their own collider and at least one of them must have a rigidbody.

isKinematic : if this is selected then the gameobject will NOT be effected from forces!

isTrigger : when this is selected, there will be no collisions but gameobject will be effected by forces!

Thursday, March 13, 2014

free musics for your unity games

Here another list of pages that you can use free for your mobile games. List will be added up in time. So be sure to check this page in the future. 1) http://www.songsfromthelostland.com/#more 2) http://soundcloud.com, be sure to check search>sound>>license to listen to>>modify commercially. there you will find tons of royaly free music. 3) http://www.soundsnap.com/ 4) http://www.audionetwork.com/sound-effects 5) http://www.musicloops.com/ 6) www.incompetech.com 7) www.danosongs.com 8) www.jewelbeat.com and a free music loop that you can direclty download free from unity3d asset store: https://www.assetstore.unity3d.com/#/content/14478 and if you want to compose your own music, here are a few tools: + NI Maschine (expensive) + Reaper (DAW) + google about VST (for some Sythies ect) then buy yourself a little MIDI-Keyboard and check out YouTube for tutorials. + http://www.vst4free.com/ + http://www.reaper.fm/

best unity 2d tutorials

Hee I will gather 2d game making tutorials that I fidn interesting. List will add up in time. Be sure to check this page later. 1) a real nice tutorial for 2d games on unity3d. http://pixelnest.io/tutorials/2d-game-unity/ 2) http://makeitatyourlibrary.org/technology/make-2d-video-game-unity#.Ux1ZGfmSxHX http://makeitatyourlibrary.org/technology/make-2d-video-game-unity#.Ux1ZGfmSxHX

Thursday, March 6, 2014

isometric games - find a great tutorial

This guy here :
http://gamedevelopment.tutsplus.com/tutorials/creating-isometric-worlds-a-primer-for-game-developers--gamedev-6511

has a great tutorial on isometric gaming.

be sure to check it out :)

Unity3D Raycast with LayerMask - How layermask works? Working example of Raycasthit and RaycastHit2D and LayerMasks , both in 2D and 3D.

You can select which layers to cast raycast in Unity3D. You can exclude some layers or you can select only the ones you want.

Unity3D uses LayerMask as an 32 bit integer. This is why you also have only 32 avaible layer slots. Each of this layers are marked as bits of that 32 bit integer. So you need to do some bit

With these operators below, you can do all your LayerMask operations.
1) bit shift operator (<<)
2) bit inverse operator (~)
3) bitwise (binary) OR operator (|)

dont worry it is much easier then it sounds :)


Here is how LayerMask represented really:
0000 0000 0000 0000 0000 0000 0000 0000
first on the right one is the first Layer you see on your unity editor.
second one comes from the second on the right.,
 so goes on like this.

You have to create LayerMask in unity like this:
int  ExitButtonLayerMask = 1 << ExitButtonLayer;
ExitButtonLayer is an integer. You get the layer numbers from unity editor.
then use the Mask on your raycast, there you get your ray which only hits only the objects which reside on your chosen layers.


Here is an example class:



public class Raycast2D : MonoBehaviour {

int ExitButtonLayer;

int RateButtonLayer;

int ExitButtonLayerMask;

int RateButtonLayerMask;

int CombinedMask;

void Awake() {

//open your unity editor, and look at layers, click "Add layer" button if you need to see the layer numbers.

ExitButtonLayer = 8;

RateButtonLayer = 9;

//ok, lets add our layers. these layers will be affected when a ray hits them:

ExitButtonLayerMask = 1 << ExitButtonLayer;

RateButtonLayerMask = 1 << RateButtonLayer;



// This is the binary OR operator, this is how we combine different masks.

CombinedMask = ExitButtonLayerMask | RateButtonLayerMask;

//btw if you want to "omit" these layers above, then you must combine them first then exclude them

// like this: ~((1 << ExitButtonLayerMask) | (1 << ExitButtonLayerMask))

}



void Update() {

if (Input.GetMouseButtonDown (0)) {

//RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

//here we use our combined layer mask, so taht unity will cast a ray on the objects which are on these layer masks. Other objects wont get affected.

RaycastHit2D hit = Physics2D.GetRayIntersection (ray, Mathf.Infinity, CombinedMask);

if (hit.collider != null) { 

Debug.Log ("object hit: " + hit.collider.gameObject.name + " , Target Position: " + hit.collider.gameObject.transform.position); 

} /*else {

Debug.Log("missed");

}*/

}

}



}



examine the code above and ask me questions if you need.
also be sure to read http://forum.unity3d.com/threads/211708-Unity-2D-Raycast-from-mouse-to-screen , MelvMay MelvMay (Unity Developer) explained 2d ray hit in 3d space.


Related Unity3d Documentation Links:
1)  Physics2D.GetRayIntersection  : Cast a 3D ray against the colliders in the scene returning the first collider along the ray. (http://docs.unity3d.com/Documentation/ScriptReference/Physics2D.GetRayIntersection.html)
2) Physics2D.GetRayIntersectionAll  : Cast a 3D ray against the colliders in the scene returning all the colliders along the ray. (http://docs.unity3d.com/Documentation/ScriptReference/Physics2D.GetRayIntersectionAll.html)
3) Physics2D.GetRayIntersectionNonAlloc  : Cast a 3D ray against the colliders in the scene returning the colliders along the ray. (http://docs.unity3d.com/Documentation/ScriptReference/Physics2D.GetRayIntersectionNonAlloc.html)
4) Found a good reading on unity3d layermask issue with raycast ignore. try http://answers.unity3d.com/questions/8715/how-do-i-use-layermasks.html good article on different approaches, including bit values and operators.



Saturday, March 1, 2014

Unity3d Enum - How to loop Enum with foreach in Unity

If you want to iterate through your enum class members in Unity3d with C#,  you can  use a foreach loop.

Infact Enum class does not implement the IEnumerable interface. This means that you cannot directly loop through all of the declared values using the foreach statement.

But Enum provides a static method named as GetValues.

This gives you an array of your enum class fields.

Like say we have a enum of  unity3d  game object names, like this one:


enum UnityGameObjectNames {
myplayer = 1,
myEnemyZombie,
myFriend
}

and you want to use unity3d gameobject names in one of your functions like start or something. You can do this like this:

void Start() {
foreach (UnityGameObjectNames  unityName in UnityGameObjectNames.GetValues(typeof(UnityGameObjectNames)))
    {
Debug.Log(unityName + "  is my Unity3d Object Name");
    }
}

or you can also specify array type, so that there wont be extra boxing - unboxing. Unity also runs on mobile devices so any tiny bit of optimization may be needed.

Better set the type of array like this:

foreach (UnityGameObjectNames  unityName in ((UnityGameObjectNames[]) UnityGameObjectNames.GetValues(typeof(UnityGameObjectNames)))
    {
Debug.Log(unityName + " myObjectName");
    }




as always a few lines of sample code of Unity3d Enum and Foreach:
Sample1:

        //foreach (Madalyalar madalya in (Madalyalar[])Madalyalar.GetValues(typeof(Madalyalar)))
        foreach (Madalyalar madalya in Madalyalar.GetValues(typeof(Madalyalar)))
        {
            Debug.Log(madalya);
            //if (PlayerPrefs.GetInt("m_" + madalya, 0) == 1) {
            //}
        }


Sample 2:
int madalyaDurumu=0;
foreach (MadalyaTipleri madalya in (MadalyaTipleri[])MadalyaTipleri.GetValues(typeof(MadalyaTipleri)))
{
//kazaılmısmadalyalar listesinde var mı ?
if(kazanilmisMadalyalar.Contains(madalya)) {
continue;
}
//eger listede yok ise, playerprefs'e bak, daha önceden kaydedilmis ise listeye ekle.
            madalyaDurumu = PlayerPrefs.GetInt(madalya.ToString());
if(madalyaDurumu == 1) {
kazanilmisMadalyalar.Add(madalya);
}
}

Singleton in Unity3d

Well if you need a singleton, you can use it in Unity3d. 


here is the code:


public class MadalyaMotor : MonoBehaviour {
// Static singleton property
public static MadalyaMotor myInstance { get; private set; }

//public MadalyaMotor()
public void Awake()
{
//-- start of singleton
// First we check if there are any other instances conflicting, better be sure than sorry
if(myInstance != null && myInstance != this)
{
// If that is the case, we destroy other instances
Destroy(gameObject);
}
// Here we save our singleton instance
myInstance = this;
// Furthermore we make sure that we don't destroy between scenes (this is optional)
DontDestroyOnLoad(gameObject);
//-- end of singleton

}
}

Singleton is useful if you want a controller or want o instantiate only one object of a kind. Like audio management , score management, achievement management,.. all  must be done in a static or a singleton object.

Try messing with the code above, put it on an empty unity3d game object, make some functions and call your singleton object from those object. You can make a number of hits singleton controller for example. If you have any questions please do post here.

Well there is also a great blog about this, try http://clearcutgames.net/home/?p=437 if you want further information on singletons. That guy also explains lazy load method of singleton. If you prepfer you can load your gameobjects with lazy load logic so that your singleton object will be created whenever you need them.


Hey i also found a good code example.  Check this out. I also included some helpful page url address so that you can examine them if you want too.

static public bool isActive {
get {
return instance  != null;
}
}

static public MyGameEngine Instance {
get {
//if(instance == null)  {
// instance = Object.FindObjectOfType(typeof(MyGameEngine)) as MyGameEngine;
//}

//some helpful url addresses to check:
//http://answers.unity3d.com/questions/17916/singletons-with-coroutines.html
//http://blog.i-evaluation.com/2013/12/11/creating-game-manager-using-state-machine-and-singleton-pattern-in-unity3d/
//http://forum.unity3d.com/threads/197169-Singleton-vs-Static

if(instance == null)  {
//first time initialize
Debug.Log("instantiate singleton");
GameObject go = new GameObject("_myGameManagerSingleton");
instance = go.AddComponent<MyGameEngine>();
go.transform.position = new Vector3(-20,-20,-20);
//GameObject go  = new GameObject("myGameManagerSingleton", typeof(MyGameEngine));
DontDestroyOnLoad(go);

//Call your other functions to continue inner initialization
instance.DoOtherInitializationStuff();
}
return instance;
}
}

another example (simple yet working great at Unity3d)


private static Singleton instance = null;

 

public static Singleton Instance

{ 

    get { return instance; }   

}

       

private void Awake()

{

    // If instance already exist, destroy ourself.

    if (instance != null && instance != this)

    { 

        Destroy(gameObject);

        return;

    }

 

    // No instance exist yet? We are it.

    instance = this;

 

    // This line exist so that the Singleton would persist between scene loads.

    // Not all singletons needs that.

    DontDestroyOnLoad(gameObject); 

}