Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Can someone Convert 2 JScripts into C#

Discussion in 'Scripting' started by MarioPCG, Feb 17, 2014.

  1. MarioPCG

    MarioPCG

    Joined:
    Nov 13, 2012
    Posts:
    8
    Can Someone Convert these two scripts into C#, I'm not good with JavaScript..
    So could someone give me a helping hand.?

    Code (csharp):
    1. private var jumpSpeed:float = 18.0;
    2. private var gravity:float = 32.0;
    3. private var runSpeed:float = 15.0;
    4. private var walkSpeed:float = 45.0;
    5. private var rotateSpeed:float = 150.0;
    6.  
    7. private var grounded:boolean = false;
    8. private var moveDirection:Vector3 = Vector3.zero;
    9. private var isWalking:boolean = false;
    10. private var moveStatus:String = "idle";
    11. var trigger : GameObject;
    12. static var dead : boolean = false;
    13. private var attack;  
    14. var attackPosition : Transform;
    15.  
    16. function Start ()
    17. {
    18.    
    19. }
    20. function delay ()
    21. {
    22.     yield WaitForSeconds(5);
    23. }
    24. function Update ()
    25. {
    26.    
    27.         if(dead == false) {
    28.        
    29.             if(Input.GetKeyDown("f"))
    30.             {  
    31.                 attack= true;  
    32.                 moveStatus = "attack";
    33.                 animation.Play("punch", PlayMode.StopAll);
    34.                 //animation.Play("upperjab", PlayMode.StopAll);  
    35.                  delay();
    36.                
    37.             //  Instantiate(trigger, attackPosition.position, attackPosition.rotation);
    38.                
    39.             }
    40.        
    41.        
    42.  
    43.  
    44.         // Only allow movement and jumps while grounded
    45.         if(grounded) {
    46.             if(Input.GetKey(KeyCode.A)  (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S)) )
    47.                 {  
    48.                     animation.CrossFade("strafeLeft", 0.2);
    49.                     //animation.Play("strafeLeft", PlayMode.StopAll);
    50.                 }
    51.             if(Input.GetKey(KeyCode.D)  (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S)) )
    52.        {  
    53.             animation.CrossFade("strafeRight", 0.2);
    54.             //animation.Play("strafeRight", PlayMode.StopAll);
    55.        }
    56.                 if(moveStatus== "idle")
    57.                 {
    58.                     animation.Play("idle");
    59.                 }
    60.              
    61.                 moveDirection = new Vector3((Input.GetMouseButton(1) ? Input.GetAxis("Horizontal") : 0),0,Input.GetAxis("Vertical"));
    62.                
    63.                 // if moving forward and to the side at the same time, compensate for distance
    64.                 // TODO: may be better way to do this?
    65.                 if(Input.GetMouseButton(1)  Input.GetAxis("Horizontal")  Input.GetAxis("Vertical")) {
    66.                         moveDirection *= .7;
    67.                    
    68.                        
    69.                 }
    70.                
    71.                 moveDirection = transform.TransformDirection(moveDirection);
    72.                 moveDirection *= isWalking ? walkSpeed : runSpeed;
    73.                
    74.                 moveStatus = "idle";
    75.                 if(moveDirection != Vector3.zero) {
    76.                         moveStatus = isWalking ? "walking" : "running";
    77.                            
    78.                         }
    79.                
    80.               if( Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S)){
    81.              
    82.                 animation.CrossFade("run", 0.2);
    83.                }
    84.                 // Jump!
    85.                 //if(Input.GetButton("Jump"))
    86.                
    87.                 if (Input.GetKeyDown(KeyCode.Space)) {
    88.               animation.Play("jump", PlayMode.StopAll);
    89.                         moveDirection.y = jumpSpeed;
    90.                        
    91.                         }
    92.         }
    93.        
    94.         // Allow turning at anytime. Keep the character facing in the same direction as the Camera if the right mouse button is down.
    95.         if(Input.GetMouseButton(1)) {
    96.                 transform.rotation = Quaternion.Euler(0,Camera.main.transform.eulerAngles.y,0);
    97.         } else {
    98.                 transform.Rotate(0,Input.GetAxis("Horizontal") * rotateSpeed * Time.deltaTime, 0);
    99.                
    100.         }
    101.      
    102.        
    103.        
    104.        
    105.                
    106.                
    107.                
    108.        
    109.         // Toggle walking/running with the T key
    110.         //if(Input.GetKeyDown("t"))
    111.                 //isWalking = !isWalking;
    112.  
    113.  
    114.        
    115.        
    116.         //Apply gravity
    117.         moveDirection.y -= gravity * Time.deltaTime;
    118.  
    119.        
    120.         //Move controller
    121.         var controller:CharacterController = GetComponent(CharacterController);
    122.         var flags = controller.Move(moveDirection * Time.deltaTime);
    123.         grounded = (flags  CollisionFlags.Below) != 0;
    124.        
    125.  
    126.         }
    127.        
    128.        
    129.         if(Input.GetMouseButton(1) || Input.GetMouseButton(0)) {
    130.                 //Screen.lockCursor = true;
    131.                
    132.                 //Screen.showCursor = false;
    133.                
    134.                
    135.                 //var mouse1 = Input.mousePosition.y;
    136.                 //var mouse2 = Input.mousePosition.x;
    137.                
    138.                 }
    139.                
    140.                 //Vector3 mousePos = Input.mousePosition;
    141.         else  {
    142.                 //Screen.lockCursor = false;
    143.                 //Screen.showCursor = false;
    144.                
    145.                 //Input.mousePosition.y = mouse1;
    146.                 //Input.mousePosition.x = mouse2;
    147.                
    148.                 //Input.mousePosition = mousePos;
    149.                
    150.                 }
    151.        
    152.        
    153. }
    154.  
    155. //@script RequireComponent(CharacterController)
    Code (csharp):
    1. var target:Transform;                                                   // Target to follow
    2. var targetHeight = 1.7;                                                 // Vertical offset adjustment
    3. var distance = 12.0;                                                    // Default Distance
    4. var offsetFromWall = 0.1;                                               // Bring camera away from any colliding objects
    5. var maxDistance = 20;                                           // Maximum zoom Distance
    6. var minDistance = 0.6;                                          // Minimum zoom Distance
    7. var xSpeed = 200.0;                                                     // Orbit speed (Left/Right)
    8. var ySpeed = 200.0;                                                     // Orbit speed (Up/Down)
    9. var yMinLimit = -80;                                                    // Looking up limit
    10. var yMaxLimit = 80;                                                     // Looking down limit
    11. var zoomRate = 40;                                                      // Zoom Speed
    12. var rotationDampening = 3.0;                            // Auto Rotation speed (higher = faster)
    13. var zoomDampening = 5.0;                                        // Auto Zoom speed (Higher = faster)
    14. var collisionLayers:LayerMask = -1;             // What the camera will collide with
    15. var lockToRearOfTarget = false;                         // Lock camera to rear of target
    16. var allowMouseInputX = true;                            // Allow player to control camera angle on the X axis (Left/Right)
    17. var allowMouseInputY = true;                            // Allow player to control camera angle on the Y axis (Up/Down)
    18.  
    19. private var xDeg = 0.0;
    20. private var yDeg = 0.0;
    21. private var currentDistance;
    22. private var desiredDistance;
    23. private var correctedDistance;
    24. private var rotateBehind = false;
    25.  
    26.  
    27. @script AddComponentMenu("Camera-Control/Third Person Camera Orbit (MMORPG Like)")
    28.  
    29. function Start ()
    30. {
    31.         var angles:Vector3 = transform.eulerAngles;
    32.         xDeg = angles.x;
    33.         yDeg = angles.y;
    34.         currentDistance = distance;
    35.         desiredDistance = distance;
    36.         correctedDistance = distance;
    37.        
    38.         // Make the rigid body not change rotation
    39.         if (rigidbody)
    40.                 rigidbody.freezeRotation = true;
    41.                
    42.         if (lockToRearOfTarget)
    43.                 rotateBehind = true;
    44.  }
    45.    
    46. //Only Move camera after everything else has been updated
    47. function LateUpdate ()
    48. {
    49.  
    50.  
    51.  
    52.         // Don't do anything if target is not defined
    53.         if (!target)
    54.                 return;
    55.        
    56.         var vTargetOffset:Vector3;
    57.        
    58.          
    59.         // If either mouse buttons are down, let the mouse govern camera position
    60.         if (GUIUtility.hotControl == 0)
    61.         {
    62.                 if (Input.GetMouseButton(0) || Input.GetMouseButton(1))
    63.                 {
    64.                         //Check to see if mouse input is allowed on the axis
    65.                         if (allowMouseInputX)
    66.                                 xDeg += Input.GetAxis ("Mouse X") * xSpeed * 0.02;
    67.                         else
    68.                                 RotateBehindTarget();
    69.                         if (allowMouseInputY)
    70.                                 yDeg -= Input.GetAxis ("Mouse Y") * ySpeed * 0.02;
    71.                        
    72.                         //Interrupt rotating behind if mouse wants to control rotation
    73.                         if (!lockToRearOfTarget)
    74.                                 rotateBehind = false;
    75.                 }
    76.                
    77.         // otherwise, ease behind the target if any of the directional keys are pressed
    78.                 else if (Input.GetAxis("Vertical") != 0 || Input.GetAxis("Horizontal") != 0 || rotateBehind)
    79.                 {
    80.                         //RotateBehindTarget();
    81.                 }
    82.         }
    83.         yDeg = ClampAngle (yDeg, yMinLimit, yMaxLimit);
    84.  
    85.         // Set camera rotation
    86.         var rotation:Quaternion = Quaternion.Euler (yDeg, xDeg, 0);
    87.  
    88.         // Calculate the desired distance
    89.         desiredDistance -= Input.GetAxis ("Mouse ScrollWheel") * Time.deltaTime * zoomRate * Mathf.Abs (desiredDistance);
    90.         desiredDistance = Mathf.Clamp (desiredDistance, minDistance, maxDistance);
    91.         correctedDistance = desiredDistance;
    92.  
    93.         // Calculate desired camera position
    94.         vTargetOffset = Vector3 (0, -targetHeight, 0);
    95.         var position:Vector3 = target.position - (rotation * Vector3.forward * desiredDistance + vTargetOffset);
    96.  
    97.         // Check for collision using the true target's desired registration point as set by user using height
    98.         var collisionHit:RaycastHit;
    99.         var trueTargetPosition:Vector3 = Vector3 (target.position.x, target.position.y + targetHeight, target.position.z);
    100.  
    101.         // If there was a collision, correct the camera position and calculate the corrected distance
    102.         var isCorrected = false;
    103.         if (Physics.Linecast (trueTargetPosition, position, collisionHit, collisionLayers))
    104.         {
    105.                 // Calculate the distance from the original estimated position to the collision location,
    106.                 // subtracting out a safety "offset" distance from the object we hit.  The offset will help
    107.                 // keep the camera from being right on top of the surface we hit, which usually shows up as
    108.                 // the surface geometry getting partially clipped by the camera's front clipping plane.
    109.                 correctedDistance = Vector3.Distance (trueTargetPosition, collisionHit.point) - offsetFromWall;
    110.                 isCorrected = true;
    111.         }
    112.  
    113.         // For smoothing, lerp distance only if either distance wasn't corrected, or correctedDistance is more than currentDistance
    114.         currentDistance = !isCorrected || correctedDistance > currentDistance ? Mathf.Lerp (currentDistance, correctedDistance, Time.deltaTime * zoomDampening) : correctedDistance;
    115.  
    116.         // Keep within limits
    117.         currentDistance = Mathf.Clamp (currentDistance, minDistance, maxDistance);
    118.  
    119.         // Recalculate position based on the new currentDistance
    120.         position = target.position - (rotation * Vector3.forward * currentDistance + vTargetOffset);
    121.        
    122.         //Finally Set rotation and position of camera
    123.         transform.rotation = rotation;
    124.         transform.position = position;
    125. }
    126.  
    127. function RotateBehindTarget()
    128. {
    129.         var targetRotationAngle:float = target.eulerAngles.y;
    130.         var currentRotationAngle:float = transform.eulerAngles.y;
    131.         xDeg = Mathf.LerpAngle (currentRotationAngle, targetRotationAngle, rotationDampening * Time.deltaTime);
    132.        
    133.         // Stop rotating behind if not completed
    134.         if (targetRotationAngle == currentRotationAngle)
    135.         {
    136.                 if (!lockToRearOfTarget)
    137.                         rotateBehind = false;
    138.         }
    139.         else
    140.                 rotateBehind = true;
    141.  
    142. }
    143.  
    144.  
    145. static function ClampAngle (angle : float, min : float, max : float)
    146. {
    147.    if (angle < -360)
    148.       angle += 360;
    149.    if (angle > 360)
    150.       angle -= 360;
    151.    return Mathf.Clamp (angle, min, max);
    152. }
    Thank you :)
     

    Attached Files:

  2. Duney

    Duney

    Joined:
    Aug 19, 2013
    Posts:
    170
    You should be able to do this yourself quite easily really with a little reading. It will also help in the long run to at least make an effort in trying to convert the files rather then rely on other people.

    The main differences are declaring variables:

    Code (csharp):
    1. private var jumpSpeed:float = 18.0;
    Code (csharp):
    1. private float jumpSpeed = 18.0f;
    Declaring functions
    Code (csharp):
    1. function Start ()
    Code (csharp):
    1. void Start ()
    - void is the return type. Void means return nothing, int/float/string/whatever means you have to return that from the function.
    The general code itself should not need to much reworking really as the basic operators =/-/+/ect.. and built-in functions in unity should transfer from JScript to Unity C# quite easily.
     
  3. MarioPCG

    MarioPCG

    Joined:
    Nov 13, 2012
    Posts:
    8
    Okay, thank you.

    I've tryed doing this myself, all i get is thousand and one different errors in the script after I change it all.

    But thank you very much!.
     
  4. AShim-3D

    AShim-3D

    Joined:
    Jul 13, 2012
    Posts:
    33
  5. MarioPCG

    MarioPCG

    Joined:
    Nov 13, 2012
    Posts:
    8
    Have and it doesn't do anything.
     
  6. Duney

    Duney

    Joined:
    Aug 19, 2013
    Posts:
    170
    Assuming your adding the correct using/includes:

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    and your also declaring the class? I think the class and C# file name have to be the same or Unity seems to throw errors.

    Code (csharp):
    1. public class MYCLASSNAME : MonoBehaviour
     
  7. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    put up the ones you tried, I can try and correct them. just don't want to go through the tedious job of changing all the variables...
     
  8. MarioPCG

    MarioPCG

    Joined:
    Nov 13, 2012
    Posts:
    8
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Camera : MonoBehaviour {
    5. Transform target;                                                   // Target to follow
    6.  
    7. public float targetHeight= 1.7f;                                                 // Vertical offset adjustment
    8.  
    9. public float distance= 12.0f;                                                    // Default Distance
    10.  
    11. public float offsetFromWall= 0.1f;                                               // Bring camera away from any colliding objects
    12.  
    13. public float maxDistance= 20;                                           // Maximum zoom Distance
    14.  
    15. public float minDistance= 0.6f;                                          // Minimum zoom Distance
    16.  
    17. public float xSpeed= 200.0f;                                                     // Orbit speed (Left/Right)
    18.  
    19. public float ySpeed= 200.0f;                                                     // Orbit speed (Up/Down)
    20.  
    21. public float yMinLimit= -80;                                                    // Looking up limit
    22.  
    23. public float yMaxLimit= 80;                                                     // Looking down limit
    24.  
    25. public float zoomRate= 40;                                                      // Zoom Speed
    26.  
    27. public float rotationDampening= 3.0f;                            // Auto Rotation speed (higher = faster)
    28.  
    29. public float zoomDampening= 5.0f;                                        // Auto Zoom speed (Higher = faster)
    30.  
    31. LayerMask collisionLayers = -1;             // What the camera will collide with
    32.  
    33. public bool lockToRearOfTarget= false;                         // Lock camera to rear of target
    34.  
    35. public bool allowMouseInputX= true;                            // Allow player to control camera angle on the X axis (Left/Right)
    36.  
    37. public bool allowMouseInputY= true;                            // Allow player to control camera angle on the Y axis (Up/Down)
    38.  
    39.  
    40.  
    41. private float xDeg= 0.0f;
    42.  
    43. private float yDeg= 0.0f;
    44.  
    45. private int currentDistance;
    46.  
    47. private int desiredDistance;
    48.  
    49. private int correctedDistance;
    50.  
    51. private bool rotateBehind= false;
    52.  
    53.  
    54.  
    55.  
    56.  
    57. //@script AddComponentMenu("Camera-Control/Third Person Camera Orbit (MMORPG Like)")
    58.  
    59.  
    60.  
    61. void  Start (){
    62.  
    63.         Vector3 angles = transform.eulerAngles;
    64.  
    65.         xDeg = angles.x;
    66.  
    67.         yDeg = angles.y;
    68.  
    69.         currentDistance = distance;
    70.  
    71.         desiredDistance = distance;
    72.  
    73.         correctedDistance = distance;
    74.  
    75.        
    76.  
    77.         // Make the rigid body not change rotation
    78.  
    79.         if (rigidbody)
    80.  
    81.                 rigidbody.freezeRotation = true;
    82.  
    83.                
    84.  
    85.         if (lockToRearOfTarget)
    86.  
    87.                 rotateBehind = true;
    88.  
    89.  }
    90.  
    91.    
    92.  
    93. //Only Move camera after everything else has been updated
    94.  
    95. void  LateUpdate (){
    96.  
    97.  
    98.  
    99.  
    100.  
    101.  
    102.  
    103.         // Don't do anything if target is not defined
    104.  
    105.         if (!target)
    106.  
    107.                 return;
    108.  
    109.        
    110.  
    111.         Vector3 vTargetOffset;
    112.  
    113.        
    114.  
    115.          
    116.  
    117.         // If either mouse buttons are down, let the mouse govern camera position
    118.  
    119.         if (GUIUtility.hotControl == 0)
    120.  
    121.         {
    122.  
    123.                 if (Input.GetMouseButton(0) || Input.GetMouseButton(1))
    124.  
    125.                 {
    126.  
    127.                         //Check to see if mouse input is allowed on the axis
    128.  
    129.                         if (allowMouseInputX)
    130.  
    131.                                 xDeg += Input.GetAxis ("Mouse X") * xSpeed * 0.02f;
    132.  
    133.                         else
    134.  
    135.                                 RotateBehindTarget();
    136.  
    137.                         if (allowMouseInputY)
    138.  
    139.                                 yDeg -= Input.GetAxis ("Mouse Y") * ySpeed * 0.02f;
    140.  
    141.                        
    142.  
    143.                         //Interrupt rotating behind if mouse wants to control rotation
    144.  
    145.                         if (!lockToRearOfTarget)
    146.  
    147.                                 rotateBehind = false;
    148.  
    149.                 }
    150.  
    151.                
    152.  
    153.         // otherwise, ease behind the target if any of the directional keys are pressed
    154.  
    155.                 else if (Input.GetAxis("Vertical") != 0 || Input.GetAxis("Horizontal") != 0 || rotateBehind)
    156.  
    157.                 {
    158.  
    159.                         //RotateBehindTarget();
    160.  
    161.                 }
    162.  
    163.         }
    164.  
    165.         yDeg = ClampAngle (yDeg, yMinLimit, yMaxLimit);
    166.  
    167.  
    168.  
    169.         // Set camera rotation
    170.  
    171.         Quaternion rotation = Quaternion.Euler (yDeg, xDeg, 0);
    172.  
    173.  
    174.  
    175.         // Calculate the desired distance
    176.  
    177.         desiredDistance -= Input.GetAxis ("Mouse ScrollWheel") * Time.deltaTime * zoomRate * Mathf.Abs (desiredDistance);
    178.  
    179.         desiredDistance = Mathf.Clamp (desiredDistance, minDistance, maxDistance);
    180.  
    181.         correctedDistance = desiredDistance;
    182.  
    183.  
    184.  
    185.         // Calculate desired camera position
    186.  
    187.         vTargetOffset = Vector3 (0, -targetHeight, 0);
    188.  
    189.         Vector3 position = target.position - (rotation * Vector3.forward * desiredDistance + vTargetOffset);
    190.  
    191.  
    192.  
    193.         // Check for collision using the true target's desired registration point as set by user using height
    194.  
    195.         RaycastHit collisionHit;
    196.  
    197.         Vector3 trueTargetPosition = Vector3 (target.position.x, target.position.y + targetHeight, target.position.z);
    198.  
    199.  
    200.  
    201.         // If there was a collision, correct the camera position and calculate the corrected distance
    202.  
    203.         bool isCorrected= false;
    204.  
    205.         if (Physics.Linecast (trueTargetPosition, position, collisionHit, collisionLayers))
    206.  
    207.         {
    208.  
    209.                 // Calculate the distance from the original estimated position to the collision location,
    210.  
    211.                 // subtracting out a safety "offset" distance from the object we hit.  The offset will help
    212.  
    213.                 // keep the camera from being right on top of the surface we hit, which usually shows up as
    214.  
    215.                 // the surface geometry getting partially clipped by the camera's front clipping plane.
    216.  
    217.                 correctedDistance = Vector3.Distance (trueTargetPosition, collisionHit.point) - offsetFromWall;
    218.  
    219.                 isCorrected = true;
    220.  
    221.         }
    222.  
    223.  
    224.  
    225.         // For smoothing, lerp distance only if either distance wasn't corrected, or correctedDistance is more than currentDistance
    226.  
    227.         currentDistance = !isCorrected || correctedDistance > currentDistance ? Mathf.Lerp (currentDistance, correctedDistance, Time.deltaTime * zoomDampening) : correctedDistance;
    228.  
    229.  
    230.  
    231.         // Keep within limits
    232.  
    233.         currentDistance = Mathf.Clamp (currentDistance, minDistance, maxDistance);
    234.  
    235.  
    236.  
    237.         // Recalculate position based on the new currentDistance
    238.  
    239.         position = target.position - (rotation * Vector3.forward * currentDistance + vTargetOffset);
    240.  
    241.        
    242.  
    243.         //Finally Set rotation and position of camera
    244.  
    245.         transform.rotation = rotation;
    246.  
    247.         transform.position = position;
    248.  
    249. }
    250.  
    251.  
    252.  
    253. void  RotateBehindTarget (){
    254.  
    255.         float targetRotationAngle = target.eulerAngles.y;
    256.  
    257.         float currentRotationAngle = transform.eulerAngles.y;
    258.  
    259.         xDeg = Mathf.LerpAngle (currentRotationAngle, targetRotationAngle, rotationDampening * Time.deltaTime);
    260.  
    261.        
    262.  
    263.         // Stop rotating behind if not completed
    264.  
    265.         if (targetRotationAngle == currentRotationAngle)
    266.  
    267.         {
    268.  
    269.                 if (!lockToRearOfTarget)
    270.  
    271.                         rotateBehind = false;
    272.  
    273.         }
    274.  
    275.         else
    276.  
    277.                 rotateBehind = true;
    278.  
    279.  
    280.  
    281. }
    282.  
    283.  
    284.  
    285.  
    286.  
    287. static void  ClampAngle ( float angle ,   float min ,   float max  ){
    288.  
    289.    if (angle < -360)
    290.  
    291.       angle += 360;
    292.  
    293.    if (angle > 360)
    294.  
    295.       angle -= 360;
    296.  
    297.    return Mathf.Clamp (angle, min, max);
    298.  
    299. }
    300. }
     

    Attached Files:

    Last edited: Feb 17, 2014
  9. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    there wasn't that much wrong, small things like if you make a Vector3 in C# you need the new keyword, if you do a raycast, the RayCastHit needs the out keyword.
    and some errors i commented what and why i changed things.
    enjoy...
     

    Attached Files:

  10. MarioPCG

    MarioPCG

    Joined:
    Nov 13, 2012
    Posts:
    8
    Thank you soo much..!