Showing posts with label cocoa touch. Show all posts
Showing posts with label cocoa touch. Show all posts

Friday, August 30, 2013

Purging Documents Directory in iOS

Your local sandboxed Documents directory may get stuffed with a bunch of garbage. To purge the directory and it's contents use this simple method:

- (void)purgeDocumentsDirectory
{
    NSLog(@"Purging Documents Directory...");
    NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSError *error = nil;
    for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]) {
        [[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
    }

}

Friday, May 10, 2013

Get substring from an NSString in Objective-C

In Objective-C / Cocoa to grab a substring from an NSString based on beginning and ending characters is easy. This is helpful if you want to parse HTML, JSON, or a REST statement returning. See below:


 NSString *sStr = [NSString stringWithFormat:@"%@", assetGroups[indexPath.row]];
 NSString *name= [[[[sStr componentsSeparatedByString:@"Beginning Char(s)"] objectAtIndex:1] componentsSeparatedByString:@"End Char(s)"] objectAtIndex:0]; 
 NSString *newString = [NSString stringWithFormat:@"%@", name];

Friday, January 25, 2013

Playing Music from iOS Music Playlist with Unity3D


With this simple coding you can play a playlist on your device from your Unity3D Game. Why license royalties when you can get the user to do it for you per individual basis.  I am using this in my game Snowboarding+ (see gameplay demo above). If there is no music on your device it'll finally play the local music in your Unity 3D app. This plays the playlist called Snowboarding+

in AppController.mm (also add MediaPlayer.framework):

#include <MediaPlayer/MediaPlayer.h>


- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
[self playMusic];
}


- (void) playMusic {
  // Instantiate a music player
    MPMusicPlayerController *appPlayer = [MPMusicPlayerController applicationMusicPlayer];
    
    // Shuffle all songs
    [appPlayer setShuffleMode:MPMusicShuffleModeSongs];
    
    // Assume we will not find our playlist
    BOOL playlistFound = NO;
    
    // Get a collection of all playlists on the device
    MPMediaQuery *playlistsQuery = [MPMediaQuery playlistsQuery];
    NSArray *playlists = [playlistsQuery collections];
    NSString *plus;
    plus = @"all";
    // Check each playlist to see if it is the right one
    for (MPMediaPlaylist *playlist in playlists) {
        NSString *playlistName = [playlist valueForProperty: MPMediaPlaylistPropertyName];
        if ([playlistName isEqualToString:@"Snowboarding+"]) {
            // Add the playlist to the player's queue and get out of here
            [appPlayer setQueueWithItemCollection:playlist];
            playlistFound = YES;
            plus = @"snowboarding+";
            break;
        }
    }
    
    // If no playlist found, just play All playlist
    if (!playlistFound) {
        for (MPMediaPlaylist *playlist in playlists) {
            NSString *playlistName = [playlist valueForProperty: MPMediaPlaylistPropertyName];
            if ([playlistName isEqualToString:@"All"]) {
                // Add the playlist to the player's queue and get out of here
                [appPlayer setQueueWithItemCollection:playlist];
                playlistFound = YES;
                plus = @"all";
                break;
            }
            else
            {
                //IF NO ALL play a random song
                [appPlayer setQueueWithQuery: [MPMediaQuery songsQuery]];
                plus = @"random";
            }
        }

    }
    
    // Start playing from the beginning of the queue
    [appPlayer play];
    
    if (appPlayer.playbackState == MPMusicPlaybackStatePlaying)
{                
UnitySendMessage("Camera", "isPlaying","TRUE");
NSLog(@"%@ is playing",plus);}
            else
{
                UnitySendMessage("Camera", "isPlaying","FALSE");
NSLog(@"internal music from Unity3D App is playing");}

}
}

In Unity 3D add the following to the Script on your Camera or any game object from above:

var isMusicPlaying: boolean = false;

@script RequireComponent(AudioSource)

function Start() {
    // Delay a clip by 10 sec (44100 samples)
  #if UNITY_EDITOR || UNITY_ANDROID || UNITY_OSX
      audio.Play(44100 * 5);     
   #endif

}

function isPlaying(message:String)
 {
  if (message == "TRUE") {isMusicPlaying = true; audio.Stop(); }
  if (message == "FALSE") {isMusicPlaying = false;  audio.Play();  }

  Debug.Log("Is the Music Playing from Device? " + message);
 }

Friday, January 18, 2013

Player Movement for Simple Air Hockey Game

This segment is for simple movement for a player in an Air Hockey Game on a 3D plane. You move mouse x and y and the y corresponds on the z plane.  This is from my Air Hockey 3D game available currently in the Android, iOS and Mac App Stores.

var other : GameObject ;
var dist : float;
var hitSound : AudioClip;
var spark : Transform;
var offset : Vector2 = Vector2.zero;
function spark1()
{
Instantiate (spark, transform.position, transform.rotation);
yield WaitForSeconds(0.5);
Destroy(GameObject.Find("Sparks(clone)"));
}
function Update () {
if (Time.timeScale != 0) {
other = GameObject.Find ("Sphere");
var Menu = GameObject.Find("Menu");
var script : menu = Menu.GetComponent(menu);
  var hit : RaycastHit;  
    var up = Vector3 ((transform.position.x - other.transform.position.x) * -1 , 0,
    (transform.position.z - other.transform.position.z) * -1 );
 
    if (Input.GetAxis("Mouse Y") > 0)     dist = 0.3 +  (Input.GetAxis("Mouse Y") / 8 ) + other.rigidbody.velocity.magnitude / 80;   else
    dist = 0.15 + other.rigidbody.velocity.magnitude / 80;
 
   Debug.DrawRay(transform.position, up , Color.green);
 
    if(Physics.Raycast(transform.position, up , hit, dist)){
       
      if(hit.collider.gameObject.name == "Sphere"){
      spark1();
      AudioSource.PlayClipAtPoint(hitSound, transform.position);
      other.rigidbody.AddForce(  up * (other.rigidbody.velocity.magnitude + 20 ),  ForceMode.Impulse);
      }
    }
if (script.singlePlayer) {
Screen.showCursor = false; #if UNITY_EDITOR
if (Input.mousePosition.x >  0  &&  Input.mousePosition.x < Screen.width)
transform.position.x = Input.mousePosition.x / (Screen.width / 2.4);
if (Input.mousePosition.y >  0 && Input.mousePosition.y < (Screen.height * 0.7)) {
if (transform.position.z < 2.194 && transform.position.z > 0) {
transform.position.z =  (Input.mousePosition.y * 0.7) / ((Screen.height * 0.7) / (3.18));
}
else if (transform.position.z >= 2.194) transform.position.z = 2.193;
 else if (transform.position.z <= 0) transform.position.z = 0.0001;
}
//Debug.Log(transform.position.z);
#elif UNITY_IPHONE || UNITY_ANDROID
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) {
if (Input.mousePosition.x >  0  &&  Input.mousePosition.x < Screen.width)
transform.position.x = Input.mousePosition.x / (Screen.width / 2.4);
if (Input.mousePosition.y >  0 && Input.mousePosition.y < (Screen.height * 0.7)) {
if (transform.position.z < 2.194 && transform.position.z > 0) {
transform.position.z =  (Input.mousePosition.y * 0.7) / ((Screen.height * 0.7) / (3.18));
}
else if (transform.position.z >= 2.194) transform.position.z = 2.193;
 else if (transform.position.z <= 0) transform.position.z = 0.0001;
}
}
#endif
}
}
}

 



Generating "Always On Top" NSWindow in macOS across all detected displays

Also: Using UIKit & Cocoa Frameworks using Objective-C In m acOS or OS X , written in either Objective-C or Swift  Langues, you m...