• 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
1
Question by HolBol · Jun 29, 2011 at 04:42 PM · c#javascriptaicarwaypoint

Car- can someone help me convert this to C#?

I want to use the AICar script for the gotw car tutorial (http://www.gotow.net/andrew/blog/?page_id=78)

Now here's the script:

 // These variables allow the script to power the wheels of the car.
 var FrontLeftWheel : WheelCollider;
 var FrontRightWheel : WheelCollider;
 
 // These variables are for the gears, the array is the list of ratios. The script
 // uses the defined gear ratios to determine how much torque to apply to the wheels.
 var GearRatio : float[];
 var CurrentGear : int = 0;
 
 // These variables are just for applying torque to the wheels and shifting gears.
 // using the defined Max and Min Engine RPM, the script can determine what gear the
 // car needs to be in.
 var EngineTorque : float = 600.0;
 var MaxEngineRPM : float = 3000.0;
 var MinEngineRPM : float = 1000.0;
 private var EngineRPM : float = 0.0;
 
 // Here's all the variables for the AI, the waypoints are determined in the "GetWaypoints" function.
 // the waypoint container is used to search for all the waypoints in the scene, and the current
 // waypoint is used to determine which waypoint in the array the car is aiming for.
 var waypointContainer : GameObject;
 private var waypoints : Array;
 private var currentWaypoint : int = 0;
 
 // input steer and input torque are the values substituted out for the player input. The 
 // "NavigateTowardsWaypoint" function determines values to use for these variables to move the car
 // in the desired direction.
 private var inputSteer : float = 0.0;
 private var inputTorque : float = 0.0;
 
 function Start () {
     // I usually alter the center of mass to make the car more stable. I'ts less likely to flip this way.
     rigidbody.centerOfMass.y = -1.5;
     
     // Call the function to determine the array of waypoints. This sets up the array of points by finding
     // transform components inside of a source container.
     GetWaypoints();
 }
 
 function Update () {
     
     // This is to limith the maximum speed of the car, adjusting the drag probably isn't the best way of doing it,
     // but it's easy, and it doesn't interfere with the physics processing.
     rigidbody.drag = rigidbody.velocity.magnitude / 250;
     
     // Call the funtion to determine the desired input values for the car. This essentially steers and
     // applies gas to the engine.
     NavigateTowardsWaypoint();
     
     // Compute the engine RPM based on the average RPM of the two wheels, then call the shift gear function
     EngineRPM = (FrontLeftWheel.rpm + FrontRightWheel.rpm)/2 * GearRatio[CurrentGear];
     ShiftGears();
 
     // set the audio pitch to the percentage of RPM to the maximum RPM plus one, this makes the sound play
     // up to twice it's pitch, where it will suddenly drop when it switches gears.
     audio.pitch = Mathf.Abs(EngineRPM / MaxEngineRPM) + 1.0 ;
     // this line is just to ensure that the pitch does not reach a value higher than is desired.
     if ( audio.pitch > 2.0 ) {
         audio.pitch = 2.0;
     }
     
     // finally, apply the values to the wheels.    The torque applied is divided by the current gear, and
     // multiplied by the calculated AI input variable.
     FrontLeftWheel.motorTorque = EngineTorque / GearRatio[CurrentGear] * inputTorque;
     FrontRightWheel.motorTorque = EngineTorque / GearRatio[CurrentGear] * inputTorque;
         
     // the steer angle is an arbitrary value multiplied by the calculated AI input.
     FrontLeftWheel.steerAngle = 10 * inputSteer;
     FrontRightWheel.steerAngle = 10 * inputSteer;
 }
 
 function ShiftGears() {
     // this funciton shifts the gears of the vehcile, it loops through all the gears, checking which will make
     // the engine RPM fall within the desired range. The gear is then set to this "appropriate" value.
     if ( EngineRPM >= MaxEngineRPM ) {
         var AppropriateGear : int = CurrentGear;
         
         for ( var i = 0; i < GearRatio.length; i ++ ) {
             if ( FrontLeftWheel.rpm * GearRatio[i] < MaxEngineRPM ) {
                 AppropriateGear = i;
                 break;
             }
         }
         
         CurrentGear = AppropriateGear;
     }
     
     if ( EngineRPM <= MinEngineRPM ) {
         AppropriateGear = CurrentGear;
         
         for ( var j = GearRatio.length-1; j >= 0; j -- ) {
             if ( FrontLeftWheel.rpm * GearRatio[j] > MinEngineRPM ) {
                 AppropriateGear = j;
                 break;
             }
         }
         
         CurrentGear = AppropriateGear;
     }
 }
 
 function GetWaypoints () {
     // Now, this function basically takes the container object for the waypoints, then finds all of the transforms in it,
     // once it has the transforms, it checks to make sure it's not the container, and adds them to the array of waypoints.
     var potentialWaypoints : Array = waypointContainer.GetComponentsInChildren( Transform );
     waypoints = new Array();
     
     for ( var potentialWaypoint : Transform in potentialWaypoints ) {
         if ( potentialWaypoint != waypointContainer.transform ) {
             waypoints[ waypoints.length ] = potentialWaypoint;
         }
     }
 }
 
 function NavigateTowardsWaypoint () {
     // now we just find the relative position of the waypoint from the car transform,
     // that way we can determine how far to the left and right the waypoint is.
     var RelativeWaypointPosition : Vector3 = transform.InverseTransformPoint( Vector3( 
                                                 waypoints[currentWaypoint].position.x, 
                                                 transform.position.y, 
                                                 waypoints[currentWaypoint].position.z ) );
                                                                                 
                                                                                 
     // by dividing the horizontal position by the magnitude, we get a decimal percentage of the turn angle that we can use to drive the wheels
     inputSteer = RelativeWaypointPosition.x / RelativeWaypointPosition.magnitude;
     
     // now we do the same for torque, but make sure that it doesn't apply any engine torque when going around a sharp turn...
     if ( Mathf.Abs( inputSteer ) < 0.5 ) {
         inputTorque = RelativeWaypointPosition.z / RelativeWaypointPosition.magnitude - Mathf.Abs( inputSteer );
     }else{
         inputTorque = 0.0;
     }
     
     // this just checks if the car's position is near enough to a waypoint to count as passing it, if it is, then change the target waypoint to the
     // next in the list.
     if ( RelativeWaypointPosition.magnitude < 20 ) {
         currentWaypoint ++;
         
         if ( currentWaypoint >= waypoints.length ) {
             currentWaypoint = 0;
         }
     }
     
 }

So I need to know what this would be in c#, namely these sections:

 var waypointContainer : GameObject;
 private var waypoints : Array;
 private var currentWaypoint : int = 0;

and this one:

 function GetWaypoints () {
     // Now, this function basically takes the container object for the waypoints, then finds all of the transforms in it,
     // once it has the transforms, it checks to make sure it's not the container, and adds them to the array of waypoints.
     var potentialWaypoints : Array = waypointContainer.GetComponentsInChildren( Transform );
     waypoints = new Array();
 
     for ( var potentialWaypoint : Transform in potentialWaypoints ) {
         if ( potentialWaypoint != waypointContainer.transform ) {
             waypoints[ waypoints.length ] = potentialWaypoint;
         }
     }
 }

And finally, this one :

 function NavigateTowardsWaypoint () {
     // now we just find the relative position of the waypoint from the car transform,
     // that way we can determine how far to the left and right the waypoint is.
     var RelativeWaypointPosition : Vector3 = transform.InverseTransformPoint( Vector3( 
                                                 waypoints[currentWaypoint].position.x, 
                                                 transform.position.y, 
                                                 waypoints[currentWaypoint].position.z ) );
 
 
     // by dividing the horizontal position by the magnitude, we get a decimal percentage of the turn angle that we can use to drive the wheels
     inputSteer = RelativeWaypointPosition.x / RelativeWaypointPosition.magnitude;
 
     // now we do the same for torque, but make sure that it doesn't apply any engine torque when going around a sharp turn...
     if ( Mathf.Abs( inputSteer ) < 0.5 ) {
         inputTorque = RelativeWaypointPosition.z / RelativeWaypointPosition.magnitude - Mathf.Abs( inputSteer );
     }else{
         inputTorque = 0.0;
     }
 
     // this just checks if the car's position is near enough to a waypoint to count as passing it, if it is, then change the target waypoint to the
     // next in the list.
     if ( RelativeWaypointPosition.magnitude < 20 ) {
         currentWaypoint ++;
 
         if ( currentWaypoint >= waypoints.length ) {
             currentWaypoint = 0;
         }
     }
 
 }

Now It's not that I'm blagging for scripts- i mean, hey,t his one works. But I need this one in C#.

Comment
Add comment
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

1 Reply

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

Answer by GuyTidhar · Jun 29, 2011 at 05:06 PM

Try This: (Your file must be named as the class name (in this case: "AICar")

 using UnityEngine;

 using System.Collections;
 using System.Collections.Generic;

 public class AICar : MonoBehaviour 
 {
     // These variables allow the script to power the wheels of the car.
     public WheelCollider FrontLeftWheel;
     public WheelCollider FrontRightWheel;

 // These variables are for the gears, the array is the list of ratios. The script
 // uses the defined gear ratios to determine how much torque to apply to the wheels.
 public float[] GearRatio;
 public int CurrentGear = 0;

 // These variables are just for applying torque to the wheels and shifting gears.
 // using the defined Max and Min Engine RPM, the script can determine what gear the
 // car needs to be in.
 public float EngineTorque = 600;
 public float MaxEngineRPM = 3000;
 public float MinEngineRPM = 1000;
 
 private float EngineRPM = 0;

 // Here's all the variables for the AI, the waypoints are determined in the "GetWaypoints" function.
 // the waypoint container is used to search for all the waypoints in the scene, and the current
 // waypoint is used to determine which waypoint in the array the car is aiming for.
 public  GameObject waypointContainer;
 private List<Transform> waypoints;
 private int currentWaypoint = 0;

 // input steer and input torque are the values substituted out for the player input. The 
 // "NavigateTowardsWaypoint" function determines values to use for these variables to move the car
 // in the desired direction.
 private float inputSteer = 0;
 private float inputTorque  = 0;

 void Start () 
 {
     Vector3 centerOfMass = rigidbody.centerOfMass;
     centerOfMass.y = -1.5f;
     // I usually alter the center of mass to make the car more stable. I'ts less likely to flip this way.
     rigidbody.centerOfMass = centerOfMass;
 
     // Call the function to determine the array of waypoints. This sets up the array of points by finding
     // transform components inside of a source container.
     GetWaypoints();
 }
 
 void Update () 
 {

     // This is to limith the maximum speed of the car, adjusting the drag probably isn't the best way of doing it,
     // but it's easy, and it doesn't interfere with the physics processing.
     rigidbody.drag = rigidbody.velocity.magnitude / 250f;
 
     // Call the funtion to determine the desired input values for the car. This essentially steers and
     // applies gas to the engine.
     NavigateTowardsWaypoint();
 
     // Compute the engine RPM based on the average RPM of the two wheels, then call the shift gear function
     EngineRPM = (FrontLeftWheel.rpm + FrontRightWheel.rpm)/2f * GearRatio[CurrentGear];
     ShiftGears();
 
     // set the audio pitch to the percentage of RPM to the maximum RPM plus one, this makes the sound play
     // up to twice it's pitch, where it will suddenly drop when it switches gears.
     audio.pitch = Mathf.Abs(EngineRPM / MaxEngineRPM) + 1.0f ;
     // this line is just to ensure that the pitch does not reach a value higher than is desired.
     if ( audio.pitch > 2.0f ) {
         audio.pitch = 2.0f;
     }
 
     // finally, apply the values to the wheels. The torque applied is divided by the current gear, and
     // multiplied by the calculated AI input variable.
     FrontLeftWheel.motorTorque = EngineTorque / GearRatio[CurrentGear] * inputTorque;
     FrontRightWheel.motorTorque = EngineTorque / GearRatio[CurrentGear] * inputTorque;
 
     // the steer angle is an arbitrary value multiplied by the calculated AI input.
     FrontLeftWheel.steerAngle = 10f * inputSteer;
     FrontRightWheel.steerAngle = 10f * inputSteer;
 }

 void ShiftGears() 
 {
     int AppropriateGear;
     
     // this funciton shifts the gears of the vehcile, it loops through all the gears, checking which will make
     // the engine RPM fall within the desired range. The gear is then set to this "appropriate" value.
     if ( EngineRPM >= MaxEngineRPM ) 
     {
         AppropriateGear = CurrentGear;
 
         for ( int i = 0; i < GearRatio.Length; i ++ ) 
         {
             if ( FrontLeftWheel.rpm * GearRatio[i] < MaxEngineRPM ) 
             {
                 AppropriateGear = i;
                 break;
             }
         }
 
         CurrentGear = AppropriateGear;
     }
 
     if ( EngineRPM = 0; j -- ) 
         {
             if ( FrontLeftWheel.rpm * GearRatio[j] > MinEngineRPM ) {
                 AppropriateGear = j;
                 break;
             }
         }
 
         CurrentGear = AppropriateGear;
     }
 }
 
 void GetWaypoints () 
 {
     // Now, this function basically takes the container object for the waypoints, then finds all of the transforms in it,
     // once it has the transforms, it checks to make sure it's not the container, and adds them to the array of waypoints.
     Transform[] potentialWaypoints = waypointContainer.GetComponentsInChildren<Transform>();
     waypoints = new List<Transform>();
 
     foreach ( Transform potentialWaypoint in potentialWaypoints ) 
     {
         if ( potentialWaypoint != waypointContainer.transform )
             waypoints.Add(potentialWaypoint);
     }
 }
 
 void NavigateTowardsWaypoint () 
 {
     // now we just find the relative position of the waypoint from the car transform,
     // that way we can determine how far to the left and right the waypoint is.
     Vector3 RelativeWaypointPosition = transform.InverseTransformPoint( new Vector3( 
                                                 waypoints[currentWaypoint].position.x, 
                                                 transform.position.y, 
                                                 waypoints[currentWaypoint].position.z ) );
 
 
     // by dividing the horizontal position by the magnitude, we get a decimal percentage of the turn angle that we can use to drive the wheels
     inputSteer = RelativeWaypointPosition.x / RelativeWaypointPosition.magnitude;
 
     // now we do the same for torque, but make sure that it doesn't apply any engine torque when going around a sharp turn...
     if ( Mathf.Abs( inputSteer ) < 0.5 )
         inputTorque = RelativeWaypointPosition.z / RelativeWaypointPosition.magnitude - Mathf.Abs( inputSteer );
     else
         inputTorque = 0.0f;
 
     // this just checks if the car's position is near enough to a waypoint to count as passing it, if it is, then change the target waypoint to the
     // next in the list.
     if ( RelativeWaypointPosition.magnitude < 20 ) 
     {
         currentWaypoint ++;
 
         if ( currentWaypoint >= waypoints.Count )
             currentWaypoint = 0;
     }
 
 }
 }
Comment
Add comment · Show 5 · 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 GuyTidhar · Jun 29, 2011 at 05:17 PM 0
Share

Check out for missing "}" I see that one got away from the code section at the end...

avatar image GuyTidhar · Jun 29, 2011 at 05:18 PM 0
Share

I just copied all from the mono editor, so the code is already checked for compilation.

avatar image madcowie · Feb 01, 2015 at 02:54 AM 0
Share

Does this Script work Guy? Am I doing something wrong? It throws all sorts of errors for me.

avatar image GuyTidhar · Feb 01, 2015 at 08:20 AM 0
Share

I compiled it at Jun 29, 2011. So it basically should work but there might have been changed to the API since then.

What errors are you getting?

avatar image grootendorste · Feb 01, 2015 at 09:09 AM 0
Share

Good work, getting someone else to translate your work. I also prefer C# above Javascript.

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Why can't i access my c# class from javascript 1 Answer

Waypoint System help 1 Answer

Making a race car positioning system 5 Answers

Enemy go haywire after player approaching it, how to properly implement waypoint and chase player. 1 Answer

Check whether car has passed a point in world space 1 Answer


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