Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Wednesday, April 22, 2015

How to make camera shake in Unity3D (javascript)

Making the Camera shake in Unity3D can add much needed dramatic effects to your game. To implement you need to manipulate position and rotation in random ranges. See below:

var originPosition:Vector3;
var originRotation:Quaternion;
var shake_decay: float;
var shake_intensity: float;

function ShakeCustom(x:float, y:float){
   originPosition = transform.position;
   originRotation = transform.rotation;
   shake_intensity = x;
   shake_decay = y;
}

function LateUpdate() {
if(shake_intensity > 0){
      transform.position = originPosition + Random.insideUnitSphere * shake_intensity;
      transform.rotation = Quaternion(
      originRotation.x + Random.Range(-shake_intensity,shake_intensity)*.2,
      originRotation.y + Random.Range(-shake_intensity,shake_intensity)*.2,
      originRotation.z + Random.Range(-shake_intensity,shake_intensity)*.2,
      originRotation.w + Random.Range(-shake_intensity,shake_intensity)*.2);
      shake_intensity -= shake_decay;
  }
}

Monday, April 21, 2014

Haversine Algorithm Implementation in Java

This is to calculate from two sets of points (Latitude, and Longitude) and distance based on the Earth's diameter/radius.

Here is the Haversine Formula followed by the java code. I've added Miles, KM, Meters, CM, Feet and Yards methods as well.

Haversine
formula:
a = sin²(Δφ/2) + cos(φ1).cos(φ2).sin²(Δλ/2)
c = 2.atan2(√a, √(1−a))
d = R.c
whereφ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km)
 note that angles need to be in radians to pass to trig functions!

/**
 * This is the implementation Haversine Distance Algorithm between two places
 * @author amitapollo
 *  R = earth’s radius (mean radius = 6372.8km)
    Δlat = lat2 − lat1
    Δlong = long2 − long1
    a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
    c = 2.atan2(√a, √(1−a))
    d = R.c * (distance converstion factor*)
 * 
 * * - km, mi, m, yds
 */

import java.lang.Math.*;

public class Haversine {
    /**
     * @param args
     * arg 1- latitude 1
     * arg 2 - longitude 1
     * arg 3 - latitude 2
     * arg 4 - longitude 2
     */

    public static final double RKilometers = 6372.8; // In kilometers
    public static final double RMiles = 10256.0; // In miles

    //returns kilometers between two sets of points (lat, lon)
    public static double haversineKilometers(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RKilometers * c;
    }

//returns meters between two sets of points (lat, lon)
    public static double haversineMeters(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RKilometers * c * 1000;
    }

    //returns centimeters between two sets of points (lat, lon)
    public static double haversineCentimeters(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RKilometers * c * 1000 * 100;
    }

    //returns miles between two sets of points (lat, lon)
    public static double haversineMiles(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RMiles * c;
    }

    //returns feet between two sets of points (lat, lon)
    public static double haversineFeet(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RMiles * c * 5280;
    }

    //returns inches between two sets of points (lat, lon)
    public static double haversineInches(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RMiles * c * 5280 * 12;
    }

    //returns yards between two sets of points (lat, lon)
    public static double haversineYards(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RMiles * c * 1760;
    }

    //CONVERTS value to Radians
    private static Double toRad(Double value) {
        return value * Math.PI / 180;
    }
}

Wednesday, March 27, 2013

Change Frame Rate in Unity3D

The FPS framerate in Unity3D is easier than ever with Unity3D 3.5+.

Below is the JS and the C# code counterpart:


    function Awake () {
        // Make the game run as fast as possible in the web player
        Application.targetFrameRate = 300;
    }
public class example : MonoBehaviour {
    void Awake() {
        Application.targetFrameRate = 300;
    }
}

Tuesday, March 12, 2013

Convert a String/Text into an Integer Array in JS

In Java sometimes you have a long string of numbers or text delimited by a space or comma. This code below converts it simply into an Integer array. You can change your delimiter under split(" "); I've set it to space for default:

 String[] parts = wholef[0].split(" ");
 int[] intwholef= new int[parts.length];

 for(int n = 0; n < parts.length; n++) {
    intwholef[n] = Integer.parseInt(parts[n]);
  }

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

 



Submit Scores and Points to Game Center in Unity3D

This simple script is how to submit scores and points to the Game Center from a Unity3D Game. People use the prime31 plugin, and pay the extra money, which dumbfounds me. Just do it yourself! I've done both JS and C# implementations of the same code... Here it goes in JavaScript:



#if UNITY_IPHONE
import UnityEngine.SocialPlatforms;
#endif

//These next two methods show the leaderboard

function DoLeaderboard () {
#if UNITY_IPHONE
Social.localUser.Authenticate (ProcessAuthentication);
#endif
}

function ProcessAuthentication (success: boolean) {
#if UNITY_IPHONE
    if (success) {
        Debug.Log ("Authentication successful");
    Social.CreateLeaderboard();
Social.CreateLeaderboard().id = "YourLeaderBoardID";
Social.ShowLeaderboardUI();
    }
    else
        Debug.Log ("Failed to authenticate");
#endif
}


//these next two methods report a score to the leaderboard

function reportScoreToBoard() {
#if UNITY_IPHONE
Social.localUser.Authenticate (ReportScore);
#endif
}


function ReportScore (success: boolean) {
#if UNITY_IPHONE
    if (success) {
        
        Debug.Log ("Authentication successful");
   
    Social.CreateLeaderboard();

Social.CreateLeaderboard().id = "YourLeaderBoardID";
Social.ReportScore(PlayerPrefs.GetInt("timeElapsed"),"YourLeaderBoardID",  function(result) {
        if (result)
            Debug.Log ("Successfully reported timeElapsed, Virgin:" + PlayerPrefs.GetInt("timeElapsed"));
        else
            Debug.Log ("Failed to report timeElapsed");});

//if you want uncomment below to show leaderboard!
//Social.ShowLeaderboardUI();
    }
    else
        Debug.Log ("Failed to authenticate");
        
 #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...