Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by highend · Nov 05, 2013 at 03:48 PM · staticclampconvertingjava to c#

javascript to C# static function clamp to void

hello everyone! this my first question here so slap me around if i'm asking the wrong question or in the wrong place

i'm converting a javascript for a 3th person camera, going good till the very last part. the java script is needing this info for the camera colliding with any object the problem is that i just can't wrap my head around the ClampAngel function, i think i get the basic of "clamp" but i don't get how C# is seeing it (it's not a vector, though they are 3 different float's), therefor very difficult for me to convert it,

this is the javascript:

 // script doing other stuff here
 yDeg = ClampAngle (yDeg, yMinLimit, yMaxLimit);
  // more script doing otherstuff here
         // Check for collision using the true target's desired registration point as set by user using height
         var collisionHit:RaycastHit;
         var trueTargetPosition:Vector3 = Vector3 (target.position.x, target.position.y + targetHeight, target.position.z);
          
         // If there was a collision, correct the camera position and calculate the corrected distance
         var isCorrected = false;
         if (Physics.Linecast (trueTargetPosition, position, collisionHit, collisionLayers))
         {
                 correctedDistance = Vector3.Distance (trueTargetPosition, **collisionHit.point**) - offsetFromWall;
                 isCorrected = true;
  // more script doing other stuff here
 
     static function ClampAngle (angle : float, min : float, max : float) 
     {
        if (angle < -360)
           angle += 360;
        if (angle > 360)
           angle -= 360;
        return Mathf.Clamp (angle, min, max);
     }

i changed this in C# to (including all the var's to (public) float/bool and more)

 //other scripting here
   yDeg = ClampAngle (yDeg, yMinLimit, yMaxLimit); 

error on last line: cannot implicitly convert type:"void" to "float"

 //more otherscripting here
 // Check for collision using the true target's desired registration point as set by user using height
     RaycastHit collisionHit = new RaycastHit() ;     

error on last line: well no error no more after googling for a solution, but i don't get this line either. after looking trough some problems/answers and unity script reference on raycasting i tried this, i don't get any errors any more, still i don't know if this is the right way for this script and this line.

     Vector3 trueTargetPosition = new Vector3 (target.position.x, target.position.y + targetHeight, target.position.z);
 
     bool isCorrected = false;
     if (Physics.Linecast (trueTargetPosition, position,out collisionHit, collisionLayers)) // this is needing the raycasthit
     {
            correctedDistance = Vector3.Distance (trueTargetPosition, collisionHit.point) - offsetFromWall;  // this is needing the raycasthit to
             isCorrected = true;
     }
 //other scripting here again
 
 // function clamp angel
 `static void ClampAngle (float angle, float min, float max) {

again, after googling for a solution how to convert: no more errors. but i also don't know if this is the right convert for this script and this line.

        if (angle < -360)
       angle += 360;
        if (angle > 360)
       angle -= 360;
        return Mathf.Clamp (angle, min, max);          }
 }

error on this line: again: cannot implicitly convert type:"float" to "void" (almost the same error, now only void and float are switched)

the full scripts are below if you think the problem is somewhere else or if there are more problems full java script:

 var target:Transform;                                                   // Target to follow
 var targetHeight = 1.7;                                                 // Vertical offset adjustment
 var distance = 12.0;                                                    // Default Distance
 var offsetFromWall = 0.1;                                               // Bring camera away from any colliding objects
 var maxDistance = 20;                                           // Maximum zoom Distance
 var minDistance = 0.6;                                          // Minimum zoom Distance
 var xSpeed = 200.0;                                                     // Orbit speed (Left/Right)
 var ySpeed = 200.0;                                                     // Orbit speed (Up/Down)
 var yMinLimit = -80;                                                    // Looking up limit
 var yMaxLimit = 80;                                                     // Looking down limit
 var zoomRate = 40;                                                      // Zoom Speed
 var rotationDampening = 3.0;                            // Auto Rotation speed (higher = faster)
 var zoomDampening = 5.0;                                        // Auto Zoom speed (Higher = faster)
 var collisionLayers:LayerMask = -1;             // What the camera will collide with
 var lockToRearOfTarget = false;                         // Lock camera to rear of target
 var allowMouseInputX = true;                            // Allow player to control camera angle on the X axis (Left/Right)
 var allowMouseInputY = true;                            // Allow player to control camera angle on the Y axis (Up/Down)
  
 private var xDeg = 0.0;
 private var yDeg = 0.0;
 private var currentDistance;
 private var desiredDistance;
 private var correctedDistance;
 private var rotateBehind = false;
  
  
 @script AddComponentMenu("Camera-Control/Third Person Camera Orbit (MMORPG Like)")
  
 function Start ()
 {
         var angles:Vector3 = transform.eulerAngles;
         xDeg = angles.x;
         yDeg = angles.y;
         currentDistance = distance;
         desiredDistance = distance;
         correctedDistance = distance;
        
         // Make the rigid body not change rotation
         if (rigidbody)
                 rigidbody.freezeRotation = true;
                
         if (lockToRearOfTarget)
                 rotateBehind = true;
  }
    
 //Only Move camera after everything else has been updated
 function LateUpdate ()
 {
  
  
  
         // Don't do anything if target is not defined
         if (!target)
                 return;
        
         var vTargetOffset:Vector3;
        
          
         // If either mouse buttons are down, let the mouse govern camera position
         if (GUIUtility.hotControl == 0)
         {
                 if (Input.GetMouseButton(0) || Input.GetMouseButton(1))
                 {
                         //Check to see if mouse input is allowed on the axis
                         if (allowMouseInputX)
                                 xDeg += Input.GetAxis ("Mouse X") * xSpeed * 0.02;
                         else
                                 RotateBehindTarget();
                         if (allowMouseInputY)
                                 yDeg -= Input.GetAxis ("Mouse Y") * ySpeed * 0.02;
                        
                         //Interrupt rotating behind if mouse wants to control rotation
                         if (!lockToRearOfTarget)
                                 rotateBehind = false;
                 }
                
         // otherwise, ease behind the target if any of the directional keys are pressed
                 else if (Input.GetAxis("Vertical") != 0 || Input.GetAxis("Horizontal") != 0 || rotateBehind)
                 {
                         //RotateBehindTarget();
                 }
         }
         yDeg = ClampAngle (yDeg, yMinLimit, yMaxLimit);
  
         // Set camera rotation
         var rotation:Quaternion = Quaternion.Euler (yDeg, xDeg, 0);
  
         // Calculate the desired distance
         desiredDistance -= Input.GetAxis ("Mouse ScrollWheel") * Time.deltaTime * zoomRate * Mathf.Abs (desiredDistance);
         desiredDistance = Mathf.Clamp (desiredDistance, minDistance, maxDistance);
         correctedDistance = desiredDistance;
  
         // Calculate desired camera position
         vTargetOffset = Vector3 (0, -targetHeight, 0);
         var position:Vector3 = target.position - (rotation * Vector3.forward * desiredDistance + vTargetOffset);
  
         // Check for collision using the true target's desired registration point as set by user using height
         var collisionHit:RaycastHit;
         var trueTargetPosition:Vector3 = Vector3 (target.position.x, target.position.y + targetHeight, target.position.z);
  
         // If there was a collision, correct the camera position and calculate the corrected distance
         var isCorrected = false;
         if (Physics.Linecast (trueTargetPosition, position, collisionHit, collisionLayers))
         {
                 // Calculate the distance from the original estimated position to the collision location,
                 // subtracting out a safety "offset" distance from the object we hit.  The offset will help
                 // keep the camera from being right on top of the surface we hit, which usually shows up as
                 // the surface geometry getting partially clipped by the camera's front clipping plane.
                 correctedDistance = Vector3.Distance (trueTargetPosition, collisionHit.point) - offsetFromWall;
                 isCorrected = true;
         }
  
         // For smoothing, lerp distance only if either distance wasn't corrected, or correctedDistance is more than currentDistance
         currentDistance = !isCorrected || correctedDistance > currentDistance ? Mathf.Lerp (currentDistance, correctedDistance, Time.deltaTime * zoomDampening) : correctedDistance;
  
         // Keep within limits
         currentDistance = Mathf.Clamp (currentDistance, minDistance, maxDistance);
  
         // Recalculate position based on the new currentDistance
         position = target.position - (rotation * Vector3.forward * currentDistance + vTargetOffset);
        
         //Finally Set rotation and position of camera
         transform.rotation = rotation;
         transform.position = position;
 }
  
 function RotateBehindTarget()
 {
         var targetRotationAngle:float = target.eulerAngles.y;
         var currentRotationAngle:float = transform.eulerAngles.y;
         xDeg = Mathf.LerpAngle (currentRotationAngle, targetRotationAngle, rotationDampening * Time.deltaTime);
        
         // Stop rotating behind if not completed
         if (targetRotationAngle == currentRotationAngle)
         {
                 if (!lockToRearOfTarget)
                         rotateBehind = false;
         }
         else
                 rotateBehind = true;
  
 }
  
  
 static function ClampAngle (angle : float, min : float, max : float)
 {
    if (angle < -360)
       angle += 360;
    if (angle > 360)
       angle -= 360;
    return Mathf.Clamp (angle, min, max);
 }

full c# convert

 using UnityEngine;
 using System.Collections;
 
 public class cameralookfunction : MonoBehaviour {
 
 public Transform target;                                                   // Target to follow
 public float targetHeight = 1.7f;                                                 // Vertical offset adjustment
 public float distance = 12.0f;                                                    // Default Distance
 public float offsetFromWall = 0.1f;                                               // Bring camera away from any colliding objects
 public float maxDistance = 20f;                                           // Maximum zoom Distance
 public float minDistance = 0.6f;                                          // Minimum zoom Distance
 public float xSpeed = 200.0f;                                                     // Orbit speed (Left/Right)
 public float ySpeed = 200.0f;                                                     // Orbit speed (Up/Down)
 public float yMinLimit = -80f;                                                    // Looking up limit
 public float yMaxLimit = 80f;                                        // Looking down limit
 public float zoomRate = 40f;                                         // Zoom Speed
 public float rotationDampening = 3.0f;                                // Auto Rotation speed (higher = faster)
 public float zoomDampening = 5.0f;                                    // Auto Zoom speed (Higher = faster)
 public LayerMask collisionLayers = -1;                                 // What the camera will collide with
 public bool lockToRearOfTarget = false;                             // Lock camera to rear of target
 public bool allowMouseInputX = true;                                // Allow player to control camera angle on the X axis (Left/Right)
 public bool allowMouseInputY = true;                                // Allow player to control camera angle on the Y axis (Up/Down)
 
 private float xDeg = 0.0f;
 private float yDeg = 0.0f;
 private float currentDistance;
 private float desiredDistance;
 private float correctedDistance;
 private bool rotateBehind = false;
 
 
 // Use this for initialization
 void Start () {
     
     Vector3 angels = transform.eulerAngles;
         xDeg = angels.x;
         yDeg = angels.y;
     currentDistance = distance;
     desiredDistance = distance;
     correctedDistance = distance;
     
     if (rigidbody)
     {      rigidbody.freezeRotation = true;                    }
            
     if (lockToRearOfTarget)
     {       rotateBehind = true;                            }
 }
 
 // Update is called once per frame if anything else is updated
     void LateUpdate () {
     
     if (!target)
     {        return;            }
     
     Vector3 vTargetOffset;
     
 
 // If either mouse buttons are down, let the mouse govern camera position
     if (GUIUtility.hotControl == 0)
     {
             if (Input.GetMouseButton(0) || Input.GetMouseButton(1))
             {
                     //Check to see if mouse input is allowed on the axis
                     if (allowMouseInputX)
                             xDeg += Input.GetAxis ("Mouse X") * xSpeed * 0.02f;
                     else
                             RotateBehindTarget();
                     if (allowMouseInputY)
                             yDeg -= Input.GetAxis ("Mouse Y") * ySpeed * 0.02f;
                    
                     //Interrupt rotating behind if mouse wants to control rotation
                     if (!lockToRearOfTarget)
                             rotateBehind = false;
             }
            
     // otherwise, ease behind the target if any of the directional keys are pressed
             else if (Input.GetAxis("Vertical") != 0 || Input.GetAxis("Horizontal") != 0 || rotateBehind)
             {
                     RotateBehindTarget();
             }
     }
     yDeg = ClampAngle (yDeg, yMinLimit, yMaxLimit);
 
     // Set camera rotation
     Quaternion rotation = Quaternion.Euler (yDeg, xDeg, 0);
 
     // Calculate the desired distance
     desiredDistance -= Input.GetAxis ("Mouse ScrollWheel") * Time.deltaTime * zoomRate * Mathf.Abs (desiredDistance);
     desiredDistance = Mathf.Clamp (desiredDistance, minDistance, maxDistance);
     correctedDistance = desiredDistance;
 
     // Calculate desired camera position
     vTargetOffset = new Vector3 (0, -targetHeight, 0);
     Vector3 position = target.position - (rotation * Vector3.forward * desiredDistance + vTargetOffset);
 
     // Check for collision using the true target's desired registration point as set by user using height
     RaycastHit collisionHit = new RaycastHit() ;
     Vector3 trueTargetPosition = new Vector3 (target.position.x, target.position.y + targetHeight, target.position.z);
 
     // If there was a collision, correct the camera position and calculate the corrected distance
     bool isCorrected = false;
     if (Physics.Linecast (trueTargetPosition, position,out collisionHit, collisionLayers))
     {
             // Calculate the distance from the original estimated position to the collision location,
             // subtracting out a safety "offset" distance from the object we hit.  The offset will help
             // keep the camera from being right on top of the surface we hit, which usually shows up as
             // the surface geometry getting partially clipped by the camera's front clipping plane.
             correctedDistance = Vector3.Distance (trueTargetPosition, collisionHit.point) - offsetFromWall;
             isCorrected = true;
     }
 
     // For smoothing, lerp distance only if either distance wasn't corrected, or correctedDistance is more than currentDistance
     currentDistance = !isCorrected || correctedDistance > currentDistance ? Mathf.Lerp (currentDistance, correctedDistance, Time.deltaTime * zoomDampening) : correctedDistance;
 
     // Keep within limits
     currentDistance = Mathf.Clamp (currentDistance, minDistance, maxDistance);
 
     // Recalculate position based on the new currentDistance
     position = target.position - (rotation * Vector3.forward * currentDistance + vTargetOffset);
    
     //Finally Set rotation and position of camera
     transform.rotation = rotation;
     transform.position = position;

}

 //    function
     void RotateBehindTarget() {
 
     float targetRotationAngle = target.eulerAngles.y;
     float currentRotationAngle = transform.eulerAngles.y;
     xDeg = Mathf.LerpAngle (currentRotationAngle, targetRotationAngle, rotationDampening * Time.deltaTime);
    
     // Stop rotating behind if not completed
     if (targetRotationAngle == currentRotationAngle)
     {
             if (!lockToRearOfTarget)
                     rotateBehind = false;
     }
     else
             rotateBehind = true;
 
 }
 
 // function clamp angel
     static void ClampAngle (float angle, float min, float max) {
        if (angle < -360)
       angle += 360;
        if (angle > 360)
       angle -= 360;
        return Mathf.Clamp (angle, min, max);
     }
 }
Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image flaviusxvii · Nov 05, 2013 at 05:37 PM 0
Share

java is not a good short name for javascript. It's an entirely different language.

avatar image Huacanacha · Nov 05, 2013 at 05:47 PM 0
Share

And Javascript is not a good name for UnityScript given the subtle differences between the two that just server as a point of confusion (so I've been told anyway). Perhaps Javascript inspired UnityScript would be a good description!

avatar image highend · Nov 05, 2013 at 08:25 PM 0
Share

Noted! I have changed the title in javascript to C# because i don't know the difference between unityscript and javascript, most people will understand it this way i believe

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Huacanacha · Nov 05, 2013 at 03:56 PM

Change the return type of ClampAngle from void to float.

Javascripy/Unityscript types can be inferred rather than needing to be explicitly stated, hence the original function did not specify it's return type.

(I'm no JS programmer so forgive me if my terminology is wrong!)

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image highend · Nov 05, 2013 at 04:51 PM 0
Share

well your ter$$anonymous$$ology is right! thanks for the fast answer!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

17 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Clamping acts strange with public static values? 0 Answers

Converting script to C# 1 Answer

Unity : Singleton ScriptableObjects resets after play 1 Answer

Mathf.Clamp() not working as expected. 4 Answers

Controlling velocity of rigidbody in air 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges