2015年11月30日 星期一

Unity GUI collocation Json and Create text write Date (Unity GUI 搭配 Json和建立文字檔並寫入資訊)

TestOnGUI (C#) : 

using UnityEngine;
using System.Collections;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;

// _Book class wait write data
public class _Book {
    public int ID { get; set; }
    public string Name { get; set;}
}

// _BookDate afterwards increase _Book class data
public class _BOOKData {
    public List<_Book> book = new List<_Book>();
}

public class TestOnGUI : MonoBehaviour {

    _Book bookTest;

    void Start() {
        bookTest = new _Book();
    }

    // Input Data value
    string id = "", name = ""; 

    void OnGUI() {

        /**
         * GUI can't dirct designation _Book class parameter, so wording. 
         * Name variable only write in global.
        */
        id = GUI.TextArea(new Rect(Screen.width/Screen.width,Screen.height/Screen.height, 100, 30), id, 200);

        // int to String
        int intId;
        int.TryParse(id, out intId);
        bookTest.ID = intId;

        name = GUI.TextArea(new Rect(Screen.width / Screen.width, Screen.height / Screen.height+50f, 100, 30), name, 200);
        bookTest.Name = name;

        if (GUI.Button(new Rect(Screen.width/Screen.width, Screen.height/Screen.height+100, 100, 50),"確定")) {

            // RootLibrary add book class Date
            _BOOKData bookDate = new _BOOKData();
            bookDate.book.Add(bookTest);

            // Json Encoding
            string outPut = JsonConvert.SerializeObject(bookDate);
            print(outPut);

            // Json Decoding
            _BOOKData _lib = JsonConvert.DeserializeObject<_BOOKData>(outPut);

            foreach (_Book book in _lib.book) {
                print("ID" + book.ID);
                print("Name" + book.Name);

                for (int i = 0; i < _lib.book.Count; i++)
                {
                    print("ListDate[" + i + "]:" +_lib.book[i]);
                }
            }

            //Create text file
            string[] createTxtValue = {bookTest.ID.ToString(), bookTest.Name};
            File.WriteAllLines("C:/Users/user/Desktop/AAA.txt", createTxtValue);
        }
    }
}

結果圖:






Unity C# Create Text (文字檔)

TestCreateTxt (C#): 

using UnityEngine;
using System.Collections;
using System.IO;

public class TestCreateTxt : MonoBehaviour {
    void OnGUI() {
        if (GUI.Button(new Rect(Screen.width / Screen.width, Screen.height / Screen.height, 500, 20), "建立文件檔")) {
            string[] lines = { "First line", "Second line", "Time line" };

            File.WriteAllLines("C:/Users/user/Desktop/AAA.txt", lines);

            string text = "A class is the most powerful data type in C#. Like a structure, " +
                       "a class defines the data and behavior of the data type. ";

            File.WriteAllText("C:/Users/user/Desktop/TestTxt.txt", text);

            StreamWriter file = new StreamWriter("C:/Users/user/Desktop/test2.txt");

            foreach (string line in lines) {
                if (!line.Contains("Second")) {
                    file.WriteLine(line);
                }
            }
        }   
    }

}

結果圖:




2015年11月29日 星期日

Unity for Json


Download Newtonsoft.Json



Testjson (C#):  寫入資料

using UnityEngine;
using System.Collections;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;

/**
  * Book Class set Date ID, Name, Author.
    using System.Collections.Generic class, user liset class 
  */
public class Book
{
    public int ID;       
    public string Name;
    public string Author;

    public List<string> listDate = new List<string>(); 
}

/**
  * RootLibrary is add Date
*/
public class RootLibrary{
    public List<Book> Library = new List<Book>();
}

public class Testjson : MonoBehaviour {

void Start () {
        
        // set Date Book class value
        Book book = new Book();
        book.ID = 1;
        book.Name = "Bee";
        book.Author = "bee";
        
        // list add Date value
        book.listDate.Add("Box");
        book.listDate.Add("Bananana");
        book.listDate.Add("Ball");

        // set Date Book2 calss value is string
        Book book2 = new Book();
        book2.ID = 2;
        book2.Name = "Cat";
        book2.Author = "cat";

        // list add Date value is string
        book2.listDate.Add("Box2");
        book2.listDate.Add("Test222") ;
        book2.listDate.Add("Back");

        // RootLibrary add book class Date
        RootLibrary lib = new RootLibrary();
        lib.Library.Add(book);
        lib.Library.Add(book2);

        // Json Encoding
        string outPut = JsonConvert.SerializeObject(lib);
        print(outPut);

        // Json Decoding
        RootLibrary _lib = JsonConvert.DeserializeObject<RootLibrary>(outPut);

        foreach (Book _book in _lib.Library) {
            print("--------------");
            print("ID"+ _book.ID);
            print("Name" + _book.Name);
            print("Author:" +_book.Author);

            for (int i =0; i<_book.listDate.Count; i++) {
                print("ListDate["+i+"]:" + _book.listDate[i]);
            }
        }
    }
}

結果圖: 

























----------------------------------------------

TestjsonInquire (c#) : 收尋資料

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

// Root_Library calss set value
public class Root_Library{
    public string Type;
}

public class TestjsonInquire : MonoBehaviour {

    void Start() {

        Root_Library lib = new Root_Library();
        lib.Type = "BookLibaray";

        /**
          * Json Encoding
          *  Json set vlaue Type
        */
        string output = JsonConvert.SerializeObject(lib) ;
        print(output);

        /**
          * Json Decoding 
          * Json Inquire Type value
         */
        JObject obj = JsonConvert.DeserializeObject<JObject>(output);
        print(obj.GetValue("Type"));
        print(obj["Type"]);
    }
}

結果圖:




















----------------------------------------------

Json、Bson 綜合應用:

using UnityEngine;
using System;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;

public class Test : MonoBehaviour {

void Start () {

        var info = new List<object> {
            new {
                Date = DateTime.Now,
                name = "Moe Loli A",
                Age = 5,
                NumberA = new int[]{000,111,222},
                NumberB = new List<int> {2, 1, 0}
            },
            new {
                Date = DateTime.Now.AddDays(1),
                name = "Moe Loli B",
                Age = 7,
                NumberA = new int[]{333,444,555},
                NumberB = new List<int> {5, 4, 3}
            },
        };

        var data = new {info};

        string json = JsonConvert.SerializeObject(data, Formatting.Indented);
        JObject Jobj = JsonConvert.DeserializeObject<JObject>(json);
        print("Json: "+json);

        JArray ja = Jobj["info"] as JArray;
        foreach (JObject obj in ja) {
            DateTime date = (DateTime)obj["Date"];
            print("Json: "+data);
        }

        byte[] bson = new byte[] { };
        using (MemoryStream steam = new MemoryStream()) {
            using (BsonWriter writer = new BsonWriter(steam)) {
                new JsonSerializer().Serialize(writer, data);
            }
            bson = steam.ToArray();
        }

        JObject Bobj;

        using (var steam = new MemoryStream(bson)) {
            using (BsonReader reader = new BsonReader(steam)) {
                JsonSerializer serializer = new JsonSerializer();
                Bobj = serializer.Deserialize<JObject>(reader);
            }
        }
        print("Bson: "+ Bobj);

        JArray ja2 = Bobj["info"] as JArray;
        foreach (JObject obj in ja2) {
            DateTime date = (DateTime)obj["Date"];
            print("Bson: "+date);
        }
    }
}

結果圖: 


























2015年11月27日 星期五

Unity Car controller / AI car (C# 版本)

Wheel Collider 詳細資料位置
Unity Car controller / AI car (JS 版本)

PlayerCar_Script  (C#) :

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(AudioSource))]
public class PlayerCar_Script : MonoBehaviour {

    // These variables allow the script to power the wheels of the car.
    [SerializeField]
    WheelCollider frontLeftWheel, frontRightWheel, backLeftWheel, backRightWheel;

    /**
      * 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.
   */
    [SerializeField]
    float[] gearRatio;
    [SerializeField]
    float differentialRatio = 3.21f;
    [SerializeField]
    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.
     */
    [SerializeField]
    float engineTorque = 600f, maxEngineRPM = 700f, minEngineRPM = 1000f, engineRPM = 0f;
    [SerializeField]
    int frontWheelDrive = 1, rearWheelDrive = 1;

    // Center Of Mass
    [SerializeField]
    float comX = 0f, comY = 0f, comZ = 0f;

    private Rigidbody rigidbody;
    private AudioSource audioSource;

    // Use this for initialization
    void Start () {
        // I usually alter the center of mass to make the car more stable. I'ts less likely to flip this way.
        rigidbody = GetComponent<Rigidbody>();
        rigidbody.centerOfMass = new Vector3(comX, comY, comZ);

        audioSource = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update () {
        //update center of mass
        rigidbody.centerOfMass = new Vector3(comX, comY, comZ);

        /**
          * 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;

        // Compute the engine RPM based on the average RPM of the two wheels, then call the shift gear function
        engineRPM = Mathf.Abs(backLeftWheel.rpm + backRightWheel.rpm) / 2 * gearRatio[currentGear] * differentialRatio;
        if (engineRPM > 10000)
            engineRPM = 10000;
        if (engineRPM < 0)
            engineRPM = 0;
        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.
        */
        audioSource.pitch = Mathf.Abs(engineRPM / maxEngineRPM) + 0.5f;
        if (audioSource.pitch > 1.5f) 
            audioSource.pitch = 1.5f;

        /**
          * finally, apply the values to the wheels. The torque applied is divided by the current gear, and
            multiplied by the user input variable.
        */
        if (frontWheelDrive.Equals(1)) {
            frontLeftWheel.motorTorque = -engineTorque * gearRatio[currentGear] * differentialRatio * Input.GetAxis("Vertical");
            frontRightWheel.motorTorque = -engineTorque * gearRatio[currentGear] * differentialRatio * Input.GetAxis("Vertical");
        }
        if (rearWheelDrive.Equals(1)) {
            backLeftWheel.motorTorque = -engineTorque * gearRatio[currentGear] * differentialRatio * Input.GetAxis("Vertical");
            backLeftWheel.motorTorque = -engineTorque * gearRatio[currentGear] * differentialRatio * Input.GetAxis("Vertical");
        }

        // the steer angle is an arbitrary value multiplied by the user input.
        frontLeftWheel.steerAngle = 35 * Input.GetAxis("Horizontal");
        frontRightWheel.steerAngle = 35 * Input.GetAxis("Horizontal");

    }

    void 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)
        {
            int appropriateGear = currentGear;
            for (int i = 0; i < gearRatio.Length; i++)
            {
                if (Mathf.Abs(backLeftWheel.rpm + backRightWheel.rpm) / 2 * gearRatio[i] * differentialRatio < maxEngineRPM)
                {
                    appropriateGear = i;
                    break;
                }
            }
            currentGear = appropriateGear;
        }
    }
}

------------------------------------------------

WheelAntiRoll_Script(C#):

using UnityEngine;
using System.Collections;

public class WheelAntiRoll_Script : MonoBehaviour {

    // Car two Wheel
    [SerializeField]
    WheelCollider wheelL, wheelR;  

    [SerializeField]
    float AntiRoll = 5000.0f;

    private Rigidbody rigidbody;

    void Start() {
        rigidbody = GetComponent<Rigidbody>();
    }

    void FixedUpdate() {

        WheelHit hits;

        bool groundedL = wheelL.GetGroundHit(out hits);

        float travelL = 1.0f;
        float travelR = 1.0f;
  
        if (groundedL) 
            travelL = (-wheelL.transform.InverseTransformPoint(hits.point).y - wheelL.radius) / wheelL.suspensionDistance;

        bool groundedR = wheelR.GetGroundHit(out hits);
        if (groundedR)
            travelR = (-wheelR.transform.InverseTransformPoint(hits.point).y - wheelR.radius) / wheelR.suspensionDistance;

        float antiRollForce = (travelL - travelR) * AntiRoll;

        if (groundedL)
            rigidbody.AddForceAtPosition(wheelL.transform.up * - antiRollForce, wheelR.transform.position);

        if (groundedR)
            rigidbody.AddForceAtPosition(wheelR.transform.up * antiRollForce, wheelR.transform.position);
    }
}
------------------------------------------------

WheelAlignment_Script (C#) :

using UnityEngine;
using System.Collections;

public class WheelAlignment_Script : MonoBehaviour {

    [SerializeField]
    WheelCollider correspondingCollider;
    [SerializeField]
    GameObject slipSmoke;

    float rotationValue = 0f;
    void FixedUpdate()
    {

        // define a hit point for the raycast collision
        RaycastHit hits;

        /**
          * Find the collider's center point, you need to do this because the center of the collider might not actually be
            the real position if the transform's off.
        */
        Vector3 colliderCenterPoint = correspondingCollider.transform.TransformPoint(correspondingCollider.center);

        /**
          * now cast a ray out from the wheel collider's center the distance of the suspension, if it hit something, then use the "hit"
            variable's data to find where the wheel hit, if it didn't, then se tthe wheel to be fully extended along the suspension.
        */
        Vector3 hitsporit = (Physics.Raycast(colliderCenterPoint, -correspondingCollider.transform.up, out hits, correspondingCollider.suspensionDistance + correspondingCollider.radius)) ? hits.point + (correspondingCollider.transform.up * correspondingCollider.radius) : colliderCenterPoint - (correspondingCollider.transform.up * correspondingCollider.suspensionDistance);
        transform.position = hitsporit;

        /**
          * now set the wheel rotation to the rotation of the collider combined with a new rotation value. This new value
            is the rotation around the axle, and the rotation from steering input.
        */
        transform.rotation = correspondingCollider.transform.rotation * Quaternion.Euler(rotationValue, correspondingCollider.steerAngle, 0);

        // increase the rotation value by the rotation speed (in degrees per second)
        rotationValue += correspondingCollider.rpm * (360 / 60) * Time.deltaTime;

        /**
          * define a wheelhit object, this stores all of the data from the wheel collider and will allow us to determine
            the slip of the tire.
        */
        WheelHit wheelhits;
        correspondingCollider.GetGroundHit(out wheelhits);


        /**
         * if the slip of the tire is greater than 2.0, and the slip prefab exists, create an instance of it on the ground at
            a zero rotation.
        */
        if (Mathf.Abs(wheelhits.sidewaysSlip) > 2)
        {
            if (slipSmoke)
                Instantiate(slipSmoke, wheelhits.point, Quaternion.identity);
            }
        }
    }

------------------------------------------------

WheelFriction_Script (C#) :

using UnityEngine;
using System.Collections;

public class WheelFriction_Script : MonoBehaviour {

    [SerializeField]
    WheelCollider frontLeftWheel, frontRightWheel, backLeftWheel, backRightWheel;

    // Wheel Friction curves
    [SerializeField]
    float forwardExtremumSlip = 10f,   //1.0f
          forwardExtremumValue = 100f, //20000.0f
          forwardAsymptoteSlip = 100f, //2.0f
          forwardAsymptoteValue = 1f,  //10000.0f
          forwardStiffness = 1.0f,
          sidewaysExtremumSlip = 6f,    //1.0f
          sidewaysExtremumValue = 100f, //20000.0f
          sidewaysAsymptoteSlip = 30f,  //2.0f
          sidewaysAsymptoteValue = 1,   //1000f
          sidewaysStiffness = 2.0f;

    WheelFrictionCurve frontLeftWheelFrictionCurve, frontRightWheelFrictionCurv, backLeftWheelFrictionCurv, backRightWheelFrictionCurv;
    Rigidbody rigidbody;


    void Start() {
        frontLeftWheelFrictionCurve = frontLeftWheel.forwardFriction;
        frontRightWheelFrictionCurv = frontRightWheel.forwardFriction;
        backLeftWheelFrictionCurv = backLeftWheel.forwardFriction;
        backRightWheelFrictionCurv = backRightWheel.forwardFriction;
        rigidbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update () {

        // Forward Friction
        frontLeftWheelFrictionCurve.extremumSlip = forwardAsymptoteSlip;
        frontLeftWheelFrictionCurve.extremumValue = forwardExtremumValue;
        frontLeftWheelFrictionCurve.asymptoteSlip = forwardAsymptoteSlip;
        frontLeftWheelFrictionCurve.asymptoteValue = forwardAsymptoteValue;
        frontLeftWheelFrictionCurve.stiffness = forwardStiffness;

        frontRightWheelFrictionCurv.extremumSlip = forwardAsymptoteSlip;
        frontRightWheelFrictionCurv.extremumValue = forwardExtremumValue;
        frontRightWheelFrictionCurv.asymptoteSlip = forwardAsymptoteSlip;
        frontRightWheelFrictionCurv.asymptoteValue = forwardAsymptoteValue;
        frontRightWheelFrictionCurv.stiffness = forwardStiffness;

        backLeftWheelFrictionCurv.extremumSlip = forwardExtremumSlip;
        backLeftWheelFrictionCurv.extremumValue = forwardExtremumValue;
        backLeftWheelFrictionCurv.asymptoteSlip = forwardAsymptoteSlip;
        backLeftWheelFrictionCurv.asymptoteValue = forwardAsymptoteValue;
        backLeftWheelFrictionCurv.stiffness = forwardStiffness;

        backRightWheelFrictionCurv.extremumSlip = forwardExtremumSlip;
        backRightWheelFrictionCurv.extremumValue = forwardExtremumValue;
        backRightWheelFrictionCurv.asymptoteSlip = forwardAsymptoteSlip;
        backRightWheelFrictionCurv.asymptoteValue = forwardAsymptoteValue;
        backRightWheelFrictionCurv.stiffness = forwardStiffness;

        //Sideways Friction
        frontLeftWheelFrictionCurve.extremumSlip = sidewaysExtremumSlip;
        frontLeftWheelFrictionCurve.extremumValue = sidewaysExtremumValue;
        frontLeftWheelFrictionCurve.asymptoteSlip = sidewaysAsymptoteSlip;
        frontLeftWheelFrictionCurve.asymptoteValue = sidewaysAsymptoteValue;
        frontLeftWheelFrictionCurve.stiffness = sidewaysStiffness;

        frontRightWheelFrictionCurv.extremumSlip = sidewaysExtremumSlip;
        frontRightWheelFrictionCurv.extremumValue = sidewaysExtremumValue;
        frontRightWheelFrictionCurv.asymptoteSlip = sidewaysAsymptoteSlip;
        frontRightWheelFrictionCurv.asymptoteValue = sidewaysAsymptoteValue;
        frontRightWheelFrictionCurv.stiffness = sidewaysStiffness;

        backLeftWheelFrictionCurv.extremumSlip = sidewaysExtremumSlip;
        backLeftWheelFrictionCurv.extremumValue = sidewaysExtremumValue;
        backLeftWheelFrictionCurv.asymptoteSlip = sidewaysAsymptoteSlip;
        backLeftWheelFrictionCurv.asymptoteValue = sidewaysAsymptoteValue;
        backLeftWheelFrictionCurv.stiffness = sidewaysStiffness;

        backRightWheelFrictionCurv.extremumSlip = sidewaysExtremumSlip;
        backRightWheelFrictionCurv.extremumValue = sidewaysExtremumValue;
        backRightWheelFrictionCurv.asymptoteSlip = sidewaysAsymptoteSlip;
        backRightWheelFrictionCurv.asymptoteValue = sidewaysAsymptoteValue;
        backRightWheelFrictionCurv.stiffness = sidewaysStiffness;
        
        // The rigidbody velocity is always given in world space, but in order to work in local space of the car model we need to transform it first.
        Vector3 relativeVelocity = transform.InverseTransformDirection(rigidbody.velocity);
        UpdateFriction(relativeVelocity);
    }

    void UpdateFriction(Vector3 relativeVelocity) {

        float sqrVel = relativeVelocity.x * relativeVelocity.x;
        
        // Forward
        int maxFStif = 100, minFStif = 70;

        frontLeftWheelFrictionCurve.extremumValue = Mathf.Clamp(maxFStif - sqrVel,0,maxFStif);
        frontLeftWheelFrictionCurve.asymptoteValue = Mathf.Clamp(minFStif - (sqrVel / 2), 0, minFStif);
        frontRightWheelFrictionCurv.extremumValue = Mathf.Clamp(maxFStif - sqrVel, 0, maxFStif);
        frontRightWheelFrictionCurv.asymptoteValue = Mathf.Clamp(minFStif - (sqrVel / 2), 0, minFStif);

        backLeftWheelFrictionCurv.extremumValue = Mathf.Clamp(maxFStif - sqrVel, 10, maxFStif);
        backLeftWheelFrictionCurv.asymptoteValue = Mathf.Clamp(minFStif - (sqrVel / 2), 10, minFStif);
        backRightWheelFrictionCurv.extremumValue = Mathf.Clamp(maxFStif - sqrVel, 10, maxFStif);
        backRightWheelFrictionCurv.asymptoteValue = Mathf.Clamp(minFStif - (sqrVel / 2), 10, minFStif);

        // Add extra sideways friction based on the car's turning velocity to avoid slipping
        int maxSStif = 100, minSStif = 50;
        frontLeftWheelFrictionCurve.extremumValue = Mathf.Clamp(maxSStif - sqrVel, 10, maxSStif);
        frontLeftWheelFrictionCurve.asymptoteValue = Mathf.Clamp(minSStif - (sqrVel / 2), 10, minSStif);
        frontRightWheelFrictionCurv.extremumValue = Mathf.Clamp(maxSStif - sqrVel, 10, maxSStif);
        frontRightWheelFrictionCurv.asymptoteValue = Mathf.Clamp(minSStif - (sqrVel / 2), 10, minSStif);

        backLeftWheelFrictionCurv.extremumValue = Mathf.Clamp(maxSStif - sqrVel, 10, maxSStif);
        backLeftWheelFrictionCurv.asymptoteValue = Mathf.Clamp(minSStif - (sqrVel / 2), 10, minSStif);
        backRightWheelFrictionCurv.extremumValue = Mathf.Clamp(maxSStif - sqrVel, 10, maxSStif);
        backRightWheelFrictionCurv.asymptoteValue = Mathf.Clamp(minSStif - (sqrVel / 2), 10, minSStif);
    }
}

------------------------------------------------

WheelSuspension_Script (C#) :

using UnityEngine;
using System.Collections;

public class WheelSuspension_Script : MonoBehaviour {

    [SerializeField]
    WheelCollider frontLeftWheel, frontRightWheel, backLeftWheel, backRightWheel;

    [SerializeField]
    float wheelRadius = 0.33f,
          springLength = 0.1f,
          damperForce = 50f,           // 50
          springForceFront = 8500f,    // 18500
          springForceRear = 5000f;     // 9000;


    JointSpring frontLeftWheelJointSpring, frontRightWheelJointSpring, backLeftWheelJointSpring, backRightWheelJointSpring;
    

    void Start() {
        frontLeftWheelJointSpring = frontLeftWheel.suspensionSpring;
        frontRightWheelJointSpring = frontRightWheel.suspensionSpring;
        backLeftWheelJointSpring = backLeftWheel.suspensionSpring;
        backRightWheelJointSpring = backRightWheel.suspensionSpring;

    }

    // Update is called once per frame
    void Update () {

        frontLeftWheel.radius = wheelRadius;
        frontLeftWheel.suspensionDistance = springLength;
        frontLeftWheelJointSpring.spring = springForceFront;
        frontLeftWheelJointSpring.damper = damperForce;

        frontRightWheel.radius = wheelRadius;
        frontRightWheel.suspensionDistance = springLength;
        frontRightWheelJointSpring.spring = springForceFront;
        frontRightWheelJointSpring.damper = damperForce;

        // Rear Suspension
        backLeftWheel.radius = wheelRadius;
        backLeftWheel.suspensionDistance = springLength;
        backLeftWheelJointSpring.spring = springLength;
        backLeftWheelJointSpring.damper = damperForce;

        backRightWheel.radius = wheelRadius;
        backRightWheel.suspensionDistance = springLength;
        backRightWheelJointSpring.spring = springLength;
        backRightWheelJointSpring.damper = damperForce;
    }
}

------------------------------------------------

AICar_Script (C#) :

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(AudioSource))]
public class AICar_Script : MonoBehaviour {

    // These variables allow the script to power the wheels of the car.
    [SerializeField]
    WheelCollider frontLeftWheel, frontRightWheel, backLeftWheel, backRightWheel;

    /**
      * 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.
    */
    [SerializeField]
    float[] gearRatio;
    [SerializeField]
    float differentialRatio = 3.1f;
    [SerializeField]
    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.
    */
    [SerializeField]
    float engineTorque = 600f,
          maxEngineRPM = 3000f,
          minEngineRPM = 1000f;
    private float engineRPM = 0f;

    /**
      * 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.
    */
    [SerializeField]
    GameObject waypointContainer;
    private 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, inputTorque;

    Rigidbody rigidbody;
    AudioSource audioSource;

    void Start () {
        // I usually alter the center of mass to make the car more stable. I'ts less likely to flip this way.
        rigidbody = GetComponent<Rigidbody>();
        rigidbody.centerOfMass = new Vector3(rigidbody.centerOfMass.x, 0.45f, 0.15f);

        audioSource = GetComponent<AudioSource>();
        /**
          * 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();
    }

    // Update is called once per frame
    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 / 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 = (backLeftWheel.rpm + backRightWheel.rpm) / 2 * gearRatio[currentGear] * differentialRatio;
        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.
        */
        audioSource.pitch = Mathf.Abs(engineRPM/maxEngineRPM)+0.5f;
        // this line is just to ensure that the pitch does not reach a value higher than is desired.
        if (audioSource.pitch > 1.5f)
            audioSource.pitch = 1.5f;

        /**
          * 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]*DifferentialRatio * inputTorque;
            FrontRightWheel.motorTorque = EngineTorque / GearRatio[CurrentGear]*DifferentialRatio * inputTorque;
        */
        backLeftWheel.motorTorque = -engineTorque / gearRatio[currentGear] * differentialRatio * inputTorque;
        backRightWheel.motorTorque = -engineTorque / gearRatio[currentGear] * differentialRatio * inputTorque;

        // the steer angle is an arbitrary value multiplied by the calculated AI input.
        frontLeftWheel.steerAngle =  35 * inputSteer;
        frontRightWheel.steerAngle = 35 * inputSteer;
    }

    void 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.
        */
        int appropriateGear;
        if (engineRPM >= maxEngineRPM){
            appropriateGear = currentGear;
            for (int i =0; i < gearRatio.Length; i++) {
                if (backLeftWheel.rpm * gearRatio[i] * differentialRatio < maxEngineRPM) {
                    appropriateGear = i;
                    break;
                }
            }
            currentGear = appropriateGear;
        }
        if (engineRPM <= minEngineRPM) {
            appropriateGear = currentGear;
            for (int j = gearRatio.Length-1; j >= 0; j--){
                if (engineRPM <= 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 Transform[];
        foreach (Transform potentialWaypoint in potentialWaypoints) {
            if (potentialWaypoint != waypointContainer.transform) 
                waypoints[waypoints.Length] = 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...
        float value = (Mathf.Abs(inputSteer) < 1.0) ? relativeWaypointPosition.z / relativeWaypointPosition.magnitude - Mathf.Abs(inputSteer) : 0f;
        inputTorque = value;

        /**
          * 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 < 30){
            currentWaypoint++;
            if (currentWaypoint >= waypoints.Length) 
                currentWaypoint = 0;
        }
    }
}

------------------------------------------------

DrawWaypointGizmos_Script (C#) :

using UnityEngine;
using System.Collections;

public class DrawWaypointGizmos_Script : MonoBehaviour {

    void OnDrawGizmos() {
        
        // make a new array of waypoints, then set it to all of the transforms in the current object
        Transform waypoints = gameObject.GetComponentInChildren<Transform>();
       
        // now loop through all of them and draw gizmos for each of them
        foreach (Transform waypoint in waypoints) {
            Gizmos.DrawSphere(waypoint.position, 1.0f);
        }
    }
}


2015年11月26日 星期四

Unity Car controller / AI car (JS 版本)

Wheel Collider 詳細資料位置

Player Car (JS):

// These variables allow the script to power the wheels of the car.
var FrontLeftWheel : WheelCollider;
var FrontRightWheel : WheelCollider;
var BackLeftWheel : WheelCollider;
var BackRightWheel : 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 DifferentialRatio : float = 3.21;
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 = 7000.0;
var MinEngineRPM : float = 1000.0;
var EngineRPM : float = 0.0;

var FrontWheelDrive : int = 1;
var RearWheelDrive : int = 1;

// Center Of Mass
var COMX : float = 0;
var COMY : float = -0.2;
var COMZ : float = 0.5;

function Start () {
// I usually alter the center of mass to make the car more stable. I'ts less likely to flip this way.
GetComponent.<Rigidbody>().centerOfMass.x = COMX;
GetComponent.<Rigidbody>().centerOfMass.y = COMY;
GetComponent.<Rigidbody>().centerOfMass.z = COMZ;
}

function Update () {
//update center of mass
GetComponent.<Rigidbody>().centerOfMass.x = COMX;
GetComponent.<Rigidbody>().centerOfMass.y = COMY;
GetComponent.<Rigidbody>().centerOfMass.z = COMZ;
// 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.
GetComponent.<Rigidbody>().drag = GetComponent.<Rigidbody>().velocity.magnitude / 250;
// Compute the engine RPM based on the average RPM of the two wheels, then call the shift gear function
EngineRPM = Mathf.Abs(BackLeftWheel.rpm + BackRightWheel.rpm)/2 * GearRatio[CurrentGear] * DifferentialRatio;
if ( EngineRPM>10000) {EngineRPM =10000;}
if ( EngineRPM<0) {EngineRPM =0;}
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.
GetComponent.<AudioSource>().pitch = Mathf.Abs(EngineRPM / MaxEngineRPM) + 0.5 ;
// this line is just to ensure that the pitch does not reach a value higher than is desired.
if ( GetComponent.<AudioSource>().pitch > 1.5 ) {
GetComponent.<AudioSource>().pitch = 1.5;
}

// finally, apply the values to the wheels. The torque applied is divided by the current gear, and
// multiplied by the user input variable.
if (FrontWheelDrive) {
FrontLeftWheel.motorTorque = -EngineTorque * GearRatio[CurrentGear]*DifferentialRatio * Input.GetAxis("Vertical");
FrontRightWheel.motorTorque = -EngineTorque * GearRatio[CurrentGear]*DifferentialRatio * Input.GetAxis("Vertical");
}
if (RearWheelDrive) {
BackLeftWheel.motorTorque = -EngineTorque * GearRatio[CurrentGear] * DifferentialRatio * Input.GetAxis("Vertical");
BackRightWheel.motorTorque = -EngineTorque * GearRatio[CurrentGear] * DifferentialRatio * Input.GetAxis("Vertical");
}

// the steer angle is an arbitrary value multiplied by the user input.
FrontLeftWheel.steerAngle = 35 * Input.GetAxis("Horizontal");
FrontRightWheel.steerAngle = 35 * Input.GetAxis("Horizontal");
}

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 ( Mathf.Abs(BackLeftWheel.rpm + BackRightWheel.rpm)/2 * GearRatio[i]*DifferentialRatio < MaxEngineRPM ) {
AppropriateGear = i;
break;
}
}
CurrentGear = AppropriateGear;
}
if ( EngineRPM <= MinEngineRPM ) {
AppropriateGear = CurrentGear;
for ( var j = GearRatio.length-1; j >= 0; j -- ) {
if ( Mathf.Abs(BackLeftWheel.rpm + BackRightWheel.rpm)/2 * GearRatio[j]*DifferentialRatio > MinEngineRPM ) {
AppropriateGear = j;
break;
}
}
CurrentGear = AppropriateGear;
}
}

----------------------------------------

※ 這是輪胎(有用前後輪,另外給參數)

WheelAntiRoll (JS):

var WheelL : WheelCollider;
var WheelR : WheelCollider;
var AntiRoll = 5000.0;

function FixedUpdate ()
    {
    var hit : WheelHit;
    var travelL = 1.0;
    var travelR = 1.0;

    var groundedL = WheelL.GetGroundHit(hit);
    if (groundedL)
        travelL = (-WheelL.transform.InverseTransformPoint(hit.point).y - WheelL.radius) / WheelL.suspensionDistance;

    var groundedR = WheelR.GetGroundHit(hit);
    if (groundedR)
        travelR = (-WheelR.transform.InverseTransformPoint(hit.point).y - WheelR.radius) / WheelR.suspensionDistance;

    var antiRollForce = (travelL - travelR) * AntiRoll;

    if (groundedL)
        GetComponent.<Rigidbody>().AddForceAtPosition(WheelL.transform.up * -antiRollForce,
               WheelL.transform.position);
    if (groundedR)
        GetComponent.<Rigidbody>().AddForceAtPosition(WheelR.transform.up * antiRollForce,
               WheelR.transform.position);
}

------------------------------------

※ 攝影機腳本

SmoothFollow(JS):

/*
This camera smoothes out rotation around the y-axis and height.
Horizontal Distance to the target is always fixed.

There are many different ways to smooth the rotation but doing it this way gives you a lot of control over how the camera behaves.

For every of those smoothed values we calculate the wanted value and the current value.
Then we smooth it using the Lerp function.
Then we apply the smoothed values to the transform's position.
*/

// The target we are following
var target : Transform;
// The distance in the x-z plane to the target
var distance = 10.0;
// the height we want the camera to be above the target
var height = 5.0;
// How much we 
var heightDamping = 2.0;
var rotationDamping = 3.0;

// Place the script in the Camera-Control group in the component menu
@script AddComponentMenu("Camera-Control/Smooth Follow")


function LateUpdate () {
// Early out if we don't have a target
if (!target)
return;

// Calculate the current rotation angles
var wantedRotationAngle = target.eulerAngles.y;
var wantedHeight = target.position.y + height;

var currentRotationAngle = transform.eulerAngles.y;
var currentHeight = transform.position.y;

// Damp the rotation around the y-axis
currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

// Damp the height
currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);

// Convert the angle into a rotation
var currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);

// Set the position of the camera on the x-z plane to:
// distance meters behind the target
transform.position = target.position;
transform.position -= currentRotation * Vector3.forward * distance;

// Set the height of the camera
transform.position.y = currentHeight;

// Always look at the target
transform.LookAt (target);
}

----------------------------------

※ 放在車子上的物件

AI Car (JS):

// These variables allow the script to power the wheels of the car.
var FrontLeftWheel : WheelCollider;
var FrontRightWheel : WheelCollider;
var BackLeftWheel : WheelCollider;
var BackRightWheel : 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 DifferentialRatio : float = 3.1;
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.
GetComponent.<Rigidbody>().centerOfMass.y = -.45;
GetComponent.<Rigidbody>().centerOfMass.z = -0.15;

// 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.
GetComponent.<Rigidbody>().drag = GetComponent.<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 = (BackLeftWheel.rpm + BackRightWheel.rpm)/2 * GearRatio[CurrentGear]*DifferentialRatio;
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.
GetComponent.<AudioSource>().pitch = Mathf.Abs(EngineRPM / MaxEngineRPM) + 0.5 ;
// this line is just to ensure that the pitch does not reach a value higher than is desired.
if ( GetComponent.<AudioSource>().pitch > 1.5 ) {
GetComponent.<AudioSource>().pitch = 1.5;
}

// 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]*DifferentialRatio * inputTorque;
//FrontRightWheel.motorTorque = EngineTorque / GearRatio[CurrentGear]*DifferentialRatio * inputTorque;
BackLeftWheel.motorTorque = -EngineTorque / GearRatio[CurrentGear]*DifferentialRatio * inputTorque;
BackRightWheel.motorTorque = -EngineTorque / GearRatio[CurrentGear]*DifferentialRatio * inputTorque;

// the steer angle is an arbitrary value multiplied by the calculated AI input.
FrontLeftWheel.steerAngle = 35 * inputSteer;
FrontRightWheel.steerAngle = 35 * 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 ( BackLeftWheel.rpm * GearRatio[i]*DifferentialRatio < MaxEngineRPM ) {
AppropriateGear = i;
break;
}
}

CurrentGear = AppropriateGear;
}

if ( EngineRPM <= MinEngineRPM ) {
AppropriateGear = CurrentGear;

for ( var j = GearRatio.length-1; j >= 0; j -- ) {
if ( BackLeftWheel.rpm * GearRatio[j]*DifferentialRatio > 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 ) < 1.0 ) {
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 < 30 ) {
currentWaypoint ++;

if ( currentWaypoint >= waypoints.length ) {
currentWaypoint = 0;
}
}


}
------------------------------------
※AI 路徑

DrawWaypointGizmos(JS):

function OnDrawGizmos () {
// make a new array of waypoints, then set it to all of the transforms in the current object
var waypoints = gameObject.GetComponentsInChildren( Transform );

// now loop through all of them and draw gizmos for each of them
for ( var waypoint : Transform in waypoints ) {
Gizmos.DrawSphere( waypoint.position, 1.0 );
}

}
-----------------------------------
介面設定:

後輪(Left):


後輪(Right):
前輪(Left): 

前輪(Right):
專案圖示: