Showing posts with label iOS. Show all posts
Showing posts with label iOS. Show all posts

Tuesday, January 19, 2016

Change Resolution pixels of iOS Game using Unity3D 5.3.1f1 in Xcode 7.x

To change the resolution in Unity 5.3.1f1 is difficult in iOS when it comes to granularity of the device. Prior to 5.3.x, you could simply put in different modes for resolution. Auto Performance, Native Resolution, and Auto Quality were some of the few.  With the new version you can not adjust this so it requires that your hands get a bit dirty.

See below in DisplayManager.mm. look for UnityScreenScaleFactor:

Modify as below:

extern "C" float UnityScreenScaleFactor(UIScreen* screen)
{
// we should query nativeScale if available to get the true device resolution
// this way we avoid unnecessarily large frame buffers and downscaling.
// e.g. iPhone 6+ pretends to be a x3 device, while its physical screen is x2.6 something.
    
    /* Amit's custom code screen size */
    float resMult = 0.75f;
    switch(UnityDeviceGeneration())
    {
        case deviceiPadPro1Gen:     resMult = 0.6f;     break;
        case deviceiPhoneUnknown:   resMult = 0.75f;    break;
        case deviceiPhone6:         resMult = 0.75f; break;
        case deviceiPhone7:         resMult = 0.75f; break;
        case deviceiPhone6Plus:     resMult = 0.6f;     break;
        case deviceiPhone6S:        resMult = 0.75f; break;
        case deviceiPhone6SPlus:    resMult = 0.6f;     break;
        case deviceiPhone4:         resMult = 0.6f; break;
        case deviceiPad3Gen:        resMult = 0.5f; break;
        case deviceiPad4Gen:        resMult = 0.5f; break;
        case deviceiPadAir1:        resMult = 0.5f; break;
        case deviceiPadAir2:        resMult = 0.5f; break;
        case deviceiPadMini2Gen:    resMult = 0.5f; break;
        case deviceiPadMini3Gen:    resMult = 0.5f; break;
        case deviceiPadUnknown:     resMult = 0.5f;     break;
        default:                    resMult = 0.8f;     break;
    }

    if([screen respondsToSelector:@selector(nativeScale)])
{
// On AppleTV screen.nativeScale returns NaN when device is in sleep mode
if (isnan(screen.nativeScale))
return 1.0f;
else
return screen.nativeScale * resMult;
}
return screen.scale * resMult;

}


As you can see above, the resMult is what you multiply the resolution accordingly. For example if you take a 0.5f multiplyer on an iPad Retina (2048x1536) it'll turn your resolution to 1/2 or 0.5 of it which is essentially 1024x768.

Why you may ask would you want to do this? Speed, simply. Some games run entirely to slow in full resolution with Unity3D. It is optimal to use a multiplyer and scale down for older devices with AA or AAA games graphics.

Sunday, December 22, 2013

Get file name and extension from URL path

How to get file name with extension in a URL path is relatively straight forward in iOS. 

The code below should work. Put your url into a NSURL variable named yourURL or whatever. Then type the below:

 NSString *JPEGfilename = [[yourURL absoluteString] lastPathComponent];

This will give you your JPEG filename or below:

 NSURL *yourURL = [NSURL urlWithString:@"http://www.hdwallpapers.in/walls/honda_v4_concept_widescreen_bike-wide.jpg"];
 NSString *JPEGfilename = [yourURL lastPathComponent];

Friday, August 30, 2013

Downloading Content to Local iOS Documents Directory

This example shows you how to download a remote file into an iOS Documents Directory from your iOS device. This is helpful for updates, and persisting data into your application, to replace static data. This allows you to keep your data fresh and dynamic.

- (void) downloadNewContent {
    NSLog(@"Downloading New Content...");
    NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"/temp"];
    NSError *error = nil;
    if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
    
    NSURL *url = [NSURL URLWithString:@"http://naep-sp2010dev.naepims.org:8889/update.zip"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    if(data) {
        stringPath = [stringPath stringByAppendingPathComponent:[url lastPathComponent]];
        [data writeToFile:stringPath atomically:YES];
    }
    

}

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];

Tuesday, March 12, 2013

Custom Transition(s) Using QuartzCore

UIStroryBoard when you push view controllers, or segues, it doesn't let you customize too much. What I ended up doing was override the perform method and used QuartzCore Animations to customize our transitions. I subclassed UIStoryBoardSegue and overwrote the perform function.

Below to customize for Push or Pop then for Segues. (For segues remember to change the class to the custom class in IB).

To do it from a normal pop or push (this does cross fade animation, adjust it for yours):


   #import <QuartzCore/QuartzCore.h>


 - (IBAction)launch1990:(id)sender {
    CATransition* transition = [CATransition animation];
    transition.duration = .45;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionFade;
    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"1990Storyboard" bundle:nil];
    UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"1990"];
    [self.navigationController pushViewController:vc animated:NO];
  }
 

To do it from segue:

 
//ZHCustomSegue.h
#import <Foundation/Foundation.h>

@interface ZHCustomSegue : UIStoryboardSegue

@end


//  ZHCustomSegue.m
#import "ZHCustomSegue.h"
#import "QuartzCore/QuartzCore.h"

@implementation ZHCustomSegue


-(void)perform {

    UIViewController *sourceViewController = (UIViewController*)[self sourceViewController];
    UIViewController *destinationController = (UIViewController*)[self destinationViewController];

    CATransition* transition = [CATransition animation];
    transition.duration = .45;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionFade; //kCATransitionMoveIn; //, kCATransitionPush,   kCATransitionReveal, kCATransitionFade
   //transition.subtype = kCATransitionFromLeft; //kCATransitionFromLeft, kCATransitionFromRight, kCATransitionFromTop, kCATransitionFromBottom



    [sourceViewController.navigationController.view.layer addAnimation:transition
                                                            forKey:kCATransition];

    [sourceViewController.navigationController pushViewController:destinationController animated:NO];
}

Vibrate Handheld in Unity3D

This simple script tells the Game/App from Unity to shake/vibrate the Device if iOS/Android. If the device doesn't support vibrate, it'll simply do nothing!:

#if UNITY_IPHONE | UNITY_ANDROID

      Handheld.Vibrate();

#endif

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
}
}
}

 



Tuesday, October 2, 2012

Using Social APIs from Unity (Leaderboard)

To submit a high score from your app to the Game Center leaderboard is easy with the Social API:
IN C# put this in your score dialog or .cs code:


void DoLeaderboard () {
    
Social.localUser.Authenticate (success => {
    
if (success) {
        Debug.Log ("Authentication successful");
        string userInfo = "Username: " + Social.localUser.userName + 
            "\nUser ID: " + Social.localUser.id + 
            "\nIsUnderage: " + Social.localUser.underage;
        Debug.Log (userInfo);
    
Social.CreateLeaderboard();
if (Application.loadedLevel == 18)
{
Social.CreateLeaderboard().id = "score18";
ReportScore(TotalScore + TotalScore2,"score18");
shown = true;
else if (Application.loadedLevel == 9)
{
Social.CreateLeaderboard().id = "score9";
ReportScore(TotalScore,"score9");
shown = true;
}
Social.ShowLeaderboardUI();
}
    else
        Debug.Log ("Authentication failed");
} );
}

void ReportScore (long score, string leaderboardID) {
    Debug.Log ("Reporting score " + score + " on leaderboard " + leaderboardID);
    Social.ReportScore (score, leaderboardID, success => {
        Debug.Log(success ? "Reported score successfully" : "Failed to report score");
    });
}

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...