Guest User

Untitled

a guest
Jun 10th, 2012
430
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Original JCar ported to JS:
  3. http://forum.unity3d.com/threads/102229-JCar-port-to-JS
  4.  
  5. Modifications by Edy 2011.10
  6. www.edy.es/unity
  7.  
  8. Modifications by Wolfos 2011
  9. www.wolfos.org
  10. */
  11.  
  12.  
  13. #pragma strict
  14. Screen.showCursor = false;
  15. enum JWheelDrive {
  16.     Front = 0,
  17.     Back = 1,
  18.     All = 2
  19. }
  20.     // if connected the controls will block if object not active
  21.     // (for example steer only if car camera is active).
  22. var postscore_url = "Ja, nee. Laten we die maar niet geven ;)";
  23. var posted = false;
  24. var highscores: String = "loading highscores";
  25. var sitedown = false;
  26.  
  27.  
  28. var checkpoint : boolean = false;
  29. var finished : boolean = false;
  30. var checkForActive : GameObject;
  31. var playtime: float = 0;
  32. var startX: float = 0;
  33. var startY: float = 0;
  34. var startZ: float = 0;
  35. var startRot: float = 0;
  36. var wheelFR : Transform; // connect to Front Right Wheel transform
  37. var wheelFL : Transform; // connect to Front Left Wheel transform
  38. var wheelBR : Transform; // connect to Back Right Wheel transform
  39. var wheelBL : Transform; // connect to Back Left Wheel transform
  40.  
  41. var wheelFRcollider : WheelCollider;    // (Edy) WheelColliders must have been already placed at their locations and referenced here.
  42. var wheelFLcollider : WheelCollider;    // This allows to place them at their correct positions (at the outer edge of the wheel).
  43. var wheelBRcollider : WheelCollider;
  44. var wheelBLcollider : WheelCollider;
  45.  
  46. var vehicleColliders : Collider[];      // (Edy) List of the colliders used for the vehicle's body (WheelColliders excluded).
  47.                                         // They are used for avoiding visual artifacts when positioning the wheel meshes.
  48.  
  49. var minSpeedTireStiffness = 0.03;   // (Edy) Variable tire stiffness settings:
  50. var minSpeedTire = 0.0;             //   if speed < minSpeedTire -> stiffness = minSpeedTireStiffness
  51. var maxSpeedTireStiffness = 0.003;  //   if speed > maxSpeedTire -> stiffness = maxSpeedTireStiffness
  52. var maxSpeedTire = 16.0;            //   proportional value if speed is between minSpeedTire and maxSpeedTire
  53.  
  54. var maxSteerAngle : float = 37.0; // max angle of steering wheels
  55.  
  56. var minSteerSpeed : float = 6.0;        // (Edy) Settings for reducing the steer angle with speed
  57. var maxSteerSpeed : float = 20.0;
  58. var maxSpeedSteerAngle : float = 12.0;
  59.  
  60.        
  61. var torque : float = 100; // the base power of the engine (per wheel, and before gears)
  62. var brakeTorque : float = 2000; // the power of the braks (per wheel)
  63. var shiftCentre : Vector3 = new Vector3(0.0, -0.25, 0.0); // offset of centre of mass
  64. var steer : float;
  65. var accel : float;
  66.  
  67. var wheelDrive : JWheelDrive = JWheelDrive.Front; // which wheels are powered
  68.    
  69. var shiftDownRPM : float  = 1500.0; // rpm script will shift gear down
  70. var shiftUpRPM : float = 2500.0; // rpm script will shift gear up
  71. var idleRPM : float = 500.0; // idle rpm
  72.    
  73.    
  74.     // gear ratios (index 0 is reverse)
  75. var gears : float[] = [-10, 9, 6, 4.5, 3, 2.5 ];
  76.    
  77.     // automatic, if true car shifts automatically up/down
  78. var automatic : boolean = true;
  79.    
  80. var killEngineSoundTimeout : float = 3.0; // time until engine sound is cut off (in s.)
  81.    
  82.     // table of efficiency at certain RPM, in tableStep RPM increases, 1.0f is 100% efficient
  83.     // at the given RPM, current table has 100% at around 2000RPM
  84. var efficiencyTable : float[] = [ 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 1.0, 1.0, 0.95, 0.80, 0.70, 0.60, 0.5, 0.45, 0.40, 0.36, 0.33, 0.30, 0.20, 0.10, 0.05 ];
  85.    
  86.     // the scale of the indices in table, so with 250f, 750RPM translates to efficiencyTable[3].
  87. var efficiencyTableStep : float = 250.0;
  88.    
  89. var currentGear :int = 1; // duh.
  90.    
  91. // shortcut to the component audiosource (engine sound).
  92. private var audioSource : AudioSource;
  93.  
  94. // every wheel has a wheeldata struct, contains useful wheel specific info
  95. class WheelData {
  96.     public var transform :  Transform;
  97.     public var col :  WheelCollider;
  98.     public var colliderOffset : float;
  99.     public var rotation : float = 0.0;
  100.     public var steer : boolean;
  101.     public var motor : boolean;
  102. };
  103.  
  104. private var wheels : WheelData[]; // array with the wheel data
  105.  
  106.  
  107.  
  108. // setup wheelcollider for given wheel data
  109. // wheel is the transform of the wheel
  110. // steer if wheel can steer or not
  111. // motor if wheel is driven by engine or not
  112. function SetWheelParams(wheel : Transform, col : WheelCollider, steer : boolean, motor : boolean) : WheelData {
  113.     if (wheel == null) {
  114.         throw new System.Exception("wheel not connected to script!");
  115.     }
  116.     var result : WheelData = new WheelData(); // the container of wheel specific data
  117.  
  118.     // store some useful references in the wheeldata object
  119.     result.transform = wheel; // access to wheel transform
  120.     result.col = col; // store the collider self
  121.     result.steer = steer; // store if wheel can steer
  122.     result.motor = motor; // store if wheel is connected to engine
  123.    
  124.     // (Edy) Store the offset between WheelCollider and wheel transform in the x axis.
  125.     // This allows to place the collider at the correct position (the outer edge of the wheel)
  126.     // and to position the wheel mesh properly later.
  127.    
  128.     result.colliderOffset = transform.InverseTransformDirection(wheel.position - col.transform.position).x;
  129.    
  130.     return result; // return the WheelData
  131. }
  132.  
  133.  
  134. // Use this for initialization
  135. function Start () {
  136.     startX = transform.position.x;
  137.     startY = transform.position.y;
  138.     startZ = transform.position.z;
  139.     //postScore("piet", 10F);
  140.     // 4 wheels, if needed different size just modify and modify
  141.     // the wheels[...] block below.
  142.     wheels = new WheelData[4];
  143.    
  144.     // setup wheels
  145.     var frontDrive : boolean = (wheelDrive == JWheelDrive.Front) || (wheelDrive == JWheelDrive.All);
  146.     var backDrive : boolean = (wheelDrive == JWheelDrive.Back) || (wheelDrive == JWheelDrive.All);
  147.    
  148.     // we use 4 wheels, but you can change that easily if neccesary.
  149.     // this is the only place that refers directly to wheelFL, ...
  150.     // so when adding wheels, you need to add the public transforms,
  151.     // adjust the array size, and add the wheels initialisation here.
  152.     wheels[0] = SetWheelParams(wheelFR, wheelFRcollider, true, frontDrive);
  153.     wheels[1] = SetWheelParams(wheelFL, wheelFLcollider, true, frontDrive);
  154.     wheels[2] = SetWheelParams(wheelBR, wheelBRcollider, false, backDrive);
  155.     wheels[3] = SetWheelParams(wheelBL, wheelBLcollider, false, backDrive);
  156.  
  157.     // we move the centre of mass (somewhere below the centre works best.)
  158.     rigidbody.centerOfMass += shiftCentre;
  159.    
  160.     // (Edy) Allow fast angular movements (default is 7), which allows more spectacular crashes.
  161.     // Forget about angular drag and artificial things like that. A proper setup and anti-roll bars will do the work.  
  162.     rigidbody.maxAngularVelocity = 10.0;
  163.    
  164.     // shortcut to audioSource should be engine sound, if null then no engine sound.
  165.     audioSource = GetComponent(AudioSource);
  166.     if (audioSource == null) {
  167.         Debug.Log("No audio source, add one to the car with looping engine noise (but can be turned off");
  168.     }
  169.     //getScores();
  170. }
  171.  
  172.  
  173. function Update() {
  174.     //print(Input.GetAxis("CSteer"));
  175.     if(!finished){
  176.         playtime += Time.deltaTime;
  177.     }
  178.     if (Input.GetKeyDown("page up")) {
  179.         ShiftUp();
  180.     }
  181.     if (Input.GetKeyDown("page down")) {
  182.         ShiftDown();
  183.     }
  184.     if (Input.GetKeyDown(KeyCode.Escape)){
  185.         Application.Quit();
  186.     }
  187.    
  188.     //if (Input.GetKeyDown(KeyCode.Return))
  189.         //{
  190.         //transform.localEulerAngles.z = 0;
  191.         //transform.position = Vector3.up * 2;
  192.     //}
  193.     if(Input.GetAxis("Reset") == 1){
  194.         reset();
  195.     }
  196.        
  197.     // (Edy)
  198.     // Apply rotation and suspension to the wheel meshes.
  199.     // It must be done inside Update (not FixedUpdate) for visual accuracy.
  200.     //
  201.     // This part can be skipped for vehicles that are either outside of the view frustrum or far away from the camera
  202.     // (or use the data calculated at FixedUpdate instead) for saving a few RayCasts per frame.
  203.        
  204.     // Avoid the Raycast to self-collide with the vehicle.
  205.        
  206.     for (var col in vehicleColliders)
  207.         col.gameObject.layer = 2;
  208.        
  209.     for (var w : WheelData in wheels)
  210.         {  
  211.         var hit : RaycastHit;
  212.        
  213.         // Locate the contact point of the tire with the nearest object underneath. If no object within the suspension distance, then the wheel is in the air.
  214.         // Then position the mesh transform at the proper position. Also apply spin and steering.
  215.        
  216.         if (Physics.Raycast(w.col.transform.position, -w.col.transform.up, hit, (w.col.suspensionDistance + w.col.radius) * w.col.transform.lossyScale.y))
  217.             w.transform.position = hit.point + w.col.transform.up * (w.col.radius * w.col.transform.lossyScale.y - 0.02) + transform.right * w.colliderOffset;
  218.         else
  219.             w.transform.position = w.col.transform.position - w.col.transform.up * (w.col.suspensionDistance * w.col.transform.lossyScale.y + 0.02) + transform.right * w.colliderOffset;
  220.            
  221.         w.rotation = Mathf.Repeat(w.rotation + Time.deltaTime * w.col.rpm * 360.0f / 60.0f, 360.0f);
  222.         w.transform.localRotation = Quaternion.Euler(w.rotation, w.col.steerAngle, 0.0f);
  223.         }
  224.        
  225.     // Place vehicle colliders back in their layer so wheels of other vehicles could intersect properly.
  226.    
  227.     for (var col in vehicleColliders)
  228.         col.gameObject.layer = 0;      
  229.        
  230.     // (Edy)
  231.     // Draw a cross mark in the Center of Mass of the vehicle.
  232.     // centerOfMass is used instead of worldCenterOfMass because the first one is interpolated according to the rigidbody's "interpolate" parameter.
  233.        
  234.     var CoM = Vector3.Scale(rigidbody.centerOfMass, Vector3(1.0/transform.localScale.x, 1.0/transform.localScale.y, 1.0/transform.localScale.z));
  235.     CoM = transform.TransformPoint(CoM);
  236.     var F = transform.forward * 0.05;
  237.     var U = transform.up * 0.05;
  238.     var R = transform.right * 0.05;
  239.        
  240.     Debug.DrawLine(CoM - F, CoM + F, Color.gray);
  241.     Debug.DrawLine(CoM - U, CoM + U, Color.gray);
  242.     Debug.DrawLine(CoM - R, CoM + R, Color.gray);
  243. }
  244.  
  245. var shiftDelay : float = 0.0;
  246.  
  247.  
  248. // handle shifting a gear up
  249. function ShiftUp() {
  250.     var now : float = Time.timeSinceLevelLoad;
  251.    
  252.     // check if we have waited long enough to shift
  253.     if (now < shiftDelay) return;
  254.    
  255.     // check if we can shift up
  256.     if (currentGear < gears.Length - 1) {
  257.         currentGear ++;
  258.        
  259.         // we delay the next shift with 1s. (sorry, hardcoded)
  260.         shiftDelay = now + 1.0;
  261.     }
  262. }
  263.  
  264. // handle shifting a gear down
  265. function ShiftDown() {
  266.     var now : float = Time.timeSinceLevelLoad;
  267.  
  268.     // check if we have waited long enough to shift
  269.     if (now < shiftDelay) return;
  270.    
  271.     // check if we can shift down (note gear 0 is reverse)
  272.     if (currentGear > 0) {
  273.         currentGear --;
  274.  
  275.         // we delay the next shift with 1/10s. (sorry, hardcoded)
  276.         shiftDelay = now + 0.1f;
  277.     }
  278. }
  279.  
  280. var wantedRPM : float = 0.0; // rpm the engine tries to reach
  281.  
  282. var motorRPM : float  = 0.0;
  283.  
  284. var killEngine : float = 0.0;
  285.  
  286. // handle the physics of the engine
  287. function FixedUpdate () {
  288.     var delta : float = Time.fixedDeltaTime;
  289.    
  290.     steer = 0; // steering -1.0 .. 1.0
  291.     accel = 0; // accelerating -1.0 .. 1.0
  292.     var brake : boolean = false; // braking (true is brake)
  293.    
  294.     if ((checkForActive == null) || checkForActive.active) {
  295.         // we only look at input when the object we monitor is
  296.         // active (or we aren't monitoring an object).
  297.         steer = Input.GetAxis("Horizontal");//InputManager.x;
  298.         if(Input.GetAxis("Horizontal") == 0){
  299.             steer = Input.GetAxis("CSteer");
  300.         }
  301.         accel = Input.GetAxis("Vertical");//InputManager.y;
  302.         if(Input.GetAxis("Vertical") == 0){
  303.             if(Input.GetAxis("CThrottle") > 0){
  304.                 accel = Input.GetAxis("CThrottle");
  305.             }
  306.             if(Input.GetAxis("CBrake") < 0){
  307.                 accel = Input.GetAxis("CBrake");
  308.             }
  309.         }
  310.         //print(accel);
  311.         brake = Input.GetButton("Jump");
  312.     }
  313.    
  314.     // handle automatic shifting
  315.     if (automatic && (currentGear == 1) && (accel < 0.0f)) {
  316.         ShiftDown(); // reverse
  317.     }
  318.     else if (automatic && (currentGear == 0) && (accel > 0.0f)) {
  319.         ShiftUp(); // go from reverse to first gear
  320.     }
  321.     else if (automatic && (motorRPM > shiftUpRPM) && (accel > 0.0f)) {
  322.         ShiftUp(); // shift up
  323.     }
  324.     else if (automatic && (motorRPM < shiftDownRPM) && (currentGear > 1)) {
  325.         ShiftDown(); // shift down
  326.     }
  327.     if (automatic && (currentGear == 0)) {
  328.         accel = -accel; // in automatic mode we need to hold arrow down for reverse
  329.     }
  330.     if (accel < 0.0) {
  331.         // if we try to decelerate we brake.
  332.         brake = true;
  333.         accel = 0.0;
  334.         wantedRPM = 0.0;
  335.     }
  336.  
  337.     // the RPM we try to achieve.
  338.     wantedRPM = (5500.0 * accel) * 0.1 + wantedRPM * 0.9;
  339.    
  340.     var rpm : float = 0.0;
  341.     var motorizedWheels : int = 0;
  342.     var floorContact : boolean = false;
  343.    
  344.     // calc rpm from current wheel speed and do some updating
  345.     for (var w : WheelData in wheels) {
  346.         var hit : WheelHit;
  347.         var col :WheelCollider = w.col;
  348.        
  349.         // only calculate rpm on wheels that are connected to engine
  350.         if (w.motor) {
  351.             rpm += col.rpm;
  352.             motorizedWheels++;
  353.             }
  354.            
  355.         // (Edy) Adjust sideways tire stiffness
  356.         // There's not much you can do about the WheelCollider bug, which hugely increases the grip with the slip.
  357.         // We can however adjust the stiffness of the sideways friction curve according to the slip providing pretty nice results.
  358.         //
  359.         // The default parameters are calculated to work with the default WheelCollider friction parameters (1, 20000, 2, 10000, 1) which, speaking of them, are just aberrant by themselves.
  360.         // Together with the WheelCollider bug, both define a tire with almost infinite grip.
  361.         // If you'd see the friction vs. slip graph for a WheelCollider with those parameters you would be atonished.
  362.        
  363.         if (col.GetGroundHit(hit))
  364.             col.sidewaysFriction.stiffness = Mathf.Lerp(minSpeedTireStiffness, maxSpeedTireStiffness, Mathf.InverseLerp(minSpeedTire, maxSpeedTire, hit.sidewaysSlip));
  365.     }
  366.     // calculate the actual motor rpm from the wheels connected to the engine
  367.     // note we haven't corrected for gear yet.
  368.     if (motorizedWheels > 1) {
  369.         rpm = rpm / motorizedWheels;
  370.     }
  371.    
  372.     // we do some delay of the change (should take delta instead of just 95% of
  373.     // previous rpm, and also adjust or gears.
  374.     motorRPM = 0.95 * motorRPM + 0.05 * Mathf.Abs(rpm * gears[currentGear]);
  375.     if (motorRPM > 5500.0) motorRPM = 5500.0;
  376.    
  377.     // calculate the 'efficiency' (low or high rpm have lower efficiency then the
  378.     // ideal efficiency, say 2000RPM, see table
  379.     var index : int = Mathf.Round(motorRPM / efficiencyTableStep);
  380.     if (index >= efficiencyTable.Length) index = efficiencyTable.Length - 1;
  381.     if (index < 0) index = 0;
  382.  
  383.     // calculate torque using gears and efficiency table
  384.     var newTorque : float = torque * gears[currentGear] * efficiencyTable[index];
  385.  
  386.     // go set torque to the wheels
  387.     for(var w : WheelData in wheels) {
  388.         col = w.col;
  389.        
  390.         // of course, only the wheels connected to the engine can get engine torque
  391.         if (w.motor) {
  392.             // only set torque if wheel goes slower than the expected speed
  393.             if (Mathf.Abs(col.rpm) > Mathf.Abs(wantedRPM)) {
  394.                 // wheel goes too fast, set torque to 0
  395.                 col.motorTorque = 0;
  396.             }
  397.             else {
  398.                 //
  399.                 var curTorque : float = col.motorTorque;
  400.                 col.motorTorque = curTorque * 0.9 + newTorque * 0.1;
  401.             }
  402.         }
  403.         // check if we have to brake
  404.         col.brakeTorque = (brake)?brakeTorque:0.0;
  405.        
  406.         // (Edy) Set steering angle. It gets limited according with the current speed.
  407.  
  408.         if (w.steer)
  409.             {
  410.             var maxSteer = Mathf.Lerp(maxSteerAngle, maxSpeedSteerAngle, Mathf.InverseLerp(minSteerSpeed, maxSteerSpeed, rigidbody.velocity.magnitude));       
  411.             col.steerAngle = steer * maxSteer;
  412.             }
  413.         else
  414.             col.steerAngle = 0.0;
  415.     }
  416.    
  417.     // if we have an audiosource (motorsound) adjust pitch using rpm        
  418.     if (audioSource != null) {
  419.         // calculate pitch (keep it within reasonable bounds)
  420.         var pitch : float = Mathf.Clamp(1.0 + ((motorRPM - idleRPM) / (shiftUpRPM - idleRPM) * 2.5), 1.0, 10.0);
  421.         audioSource.pitch = pitch;
  422.        
  423.         if (motorRPM > 100) {
  424.             // turn on sound if it's not playing yet and RPM is > 100.
  425.             if (!audioSource.isPlaying) {
  426.                 audioSource.Play();
  427.             }
  428.             // how long we should wait with engine RPM <= 100 before killing engine sound
  429.             killEngine = Time.time + killEngineSoundTimeout;
  430.         }
  431.         else if ((audioSource.isPlaying) && (Time.time > killEngine)) {
  432.             // standing still, kill engine sound.
  433.             audioSource.Stop();
  434.         }
  435.     }
  436. }
  437.  
  438. function OnGUI() {
  439.     if (checkForActive.active) {
  440.         // calculate actual speed in Km/H (SI metrics rule, so no inch, yard, foot,
  441.         // stone, or other stupid length measure!)
  442.         // Wolfos agrees and would also like to add that imperial measuring makes no sense
  443.         var speed : float = rigidbody.velocity.magnitude * 3.6;
  444.    
  445.         // message to display
  446.         var msg = String.Format("Time = " + playtime);
  447.        
  448.         //var msg : String = "Speed " + speed + "Km/H, " + motorRPM + "RPM, gear " + currentGear; //  + " torque " + newTorque.ToString("f2") + ", efficiency " + table[index].ToString("f2");
  449.  
  450.         GUILayout.BeginArea(new Rect(Screen.width - 150, 32, 130, 50), GUI.skin.window);
  451.         GUILayout.Label(msg);
  452.         GUILayout.EndArea();
  453.         if(finished){
  454.             if(!sitedown){
  455.             if(!posted){
  456.                 postScore(PlayerPrefs.GetString("Playername"), playtime);
  457.                 getScore();
  458.                 posted=true;
  459.             }
  460.             }
  461.             GUILayout.BeginArea(new Rect(Screen.width/2-85,Screen.height/2-200,170,270), GUI.skin.window);
  462.             GUILayout.Label("Your time was: " + playtime + " Press 'return' to restart or press 'escape' to load another level\n\nTop 10:\n" + highscores);
  463.             GUILayout.EndArea();
  464.         }
  465.     }
  466. }
  467.  
  468.  
  469. //Wolfos' functions start here
  470. function reset(){
  471.     /*(Wolfos) This function resets the car to the given position (usually the starting point), resets the time to 0 and
  472.     sets the checkpoint boolean to false. Speed (in al directions) is also reset.*/
  473.     transform.position = Vector3(startX,startY,startZ);
  474.     transform.rotation.x = 0;
  475.     transform.rotation.y = startRot;
  476.     transform.rotation.z = 0;
  477.     rigidbody.velocity = Vector3(0,0,0);
  478.     checkpoint = false;
  479.     finished = false;
  480.     posted=false;
  481.     playtime = 0;
  482. }
  483.  
  484. function OnCollisionEnter(collision : Collision){
  485.     //(Wolfos) This function checks for collision, specifically with "Finish" and "Checkpoint"
  486.     if(collision.gameObject.name == "Finish" && !finished && checkpoint){
  487.         finished = true;
  488.     }
  489.     if(collision.gameObject.name == "Checkpoint"){
  490.         checkpoint = true;
  491.     }
  492.     if(collision.gameObject.name == "loop"){
  493.         Camera.main.GetComponent(CamFixTo).enabled = true;
  494.     }
  495.     else{
  496.         Camera.main.GetComponent(CamFixTo).enabled = false;
  497.     }
  498. }
  499.  
  500.  
  501. function postScore(pname: String, score: float){
  502.     if(!sitedown && !posted){
  503.     var loadedlevel=Application.loadedLevelName;
  504.     var hash=Md5Sum(pname+score+loadedlevel+"Encryptie sleutel");
  505.     var my_url = postscore_url + "name=" + pname + "&score=" + score + "&levelname=" + loadedlevel + "&hash=" + hash;
  506.     //print(my_url);
  507.     var hs_post = WWW(my_url);
  508.    
  509.     yield hs_post; // Wait until the download is done
  510.     //print("posted scores");
  511.     if(hs_post.error) {
  512.         sitedown = true;
  513.         print("There was an error posting the high score: " + hs_post.error);
  514.     }
  515.     }
  516. }
  517.  
  518. function getScore(){
  519.     if(!sitedown && !posted){
  520.     var loadedlevel=Application.loadedLevelName;
  521.     var my_url = postscore_url + "list=true&levelname=" + loadedlevel;
  522.     var hs_get = WWW(my_url);
  523.     yield hs_get;
  524.    
  525.      if(hs_get.error) {
  526.         sitedown = true;
  527.         print("There was an error getting the high score: " + hs_get.error);
  528.     } else {
  529.         //print("got scores");
  530.         highscores = hs_get.text.Replace("<br />", "\n");
  531.     }
  532.     }
  533. }
  534.  
  535. static function Md5Sum(strToEncrypt: String)
  536. {
  537.     var encoding = System.Text.UTF8Encoding();
  538.     var bytes = encoding.GetBytes(strToEncrypt);
  539.  
  540.     // encrypt bytes
  541.     var md5 = System.Security.Cryptography.MD5CryptoServiceProvider();
  542.     var hashBytes:byte[] = md5.ComputeHash(bytes);
  543.  
  544.     // Convert the encrypted bytes back to a string (base 16)
  545.     var hashString = "";
  546.  
  547.     for (var i = 0; i < hashBytes.Length; i++)
  548.     {
  549.         hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, "0"[0]);
  550.     }
  551.  
  552.     return hashString.PadLeft(32, "0"[0]);
  553. }
Advertisement
Add Comment
Please, Sign In to add comment