:: Dileep's Web :: - Move and Rotate an Object (using...

24
C# for UNITY3d: Sem 1 a.k.a. The Gospel of Mark – Part 1 Special Thanks to Mark Hoey, whose lectures this booklet is based on TABLE OF CONTENTS Move and Rotate an Object (using Transform.Translate & Transform.Rotate) 1 Random Color...................................................1 Clamping (Mathf.Clamp)........................................... 2 Change Levels (scenes) & Quit Application.......................2 Move, Jump and Rotate an Object (Rigidbody to move and prevent double jumps) 3 Throw a Weapon (rigid body) – uses a timer to prevent rapid firing...........4 Instantiating (spawning) using a for loop and Bouncy Material....5 Destroy or Reposition Instantiated Objects.....................5 Binding UI elements to variables...............................6 Triggers, Collisions & Importing Scripts and variables.........7 Nav Mesh Agent.................................................7 Change Animation State using Animator..........................8 Arrays Example Script..........................................9 Ray Cast Example Script.......................................10 Three Scripts for Camera Follow, Mouse Orbit & Player Movement 11

Transcript of :: Dileep's Web :: - Move and Rotate an Object (using...

Page 1: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

C# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part 1

Special Thanks to Mark Hoey, whose lectures this booklet is based on

TABLE OF CONTENTS

Move and Rotate an Object (using Transform.Translate & Transform.Rotate)............................1

Random Color............................................................................................................................................................ 1

Clamping (Mathf.Clamp).......................................................................................................................................2

Change Levels (scenes) & Quit Application..................................................................................................2

Move, Jump and Rotate an Object (Rigidbody to move and prevent double jumps)...................3

Throw a Weapon (rigid body) – uses a timer to prevent rapid firing.................................................4

Instantiating (spawning) using a for loop and Bouncy Material.........................................................5

Destroy or Reposition Instantiated Objects.................................................................................................5

Binding UI elements to variables......................................................................................................................6

Triggers, Collisions & Importing Scripts and variables..........................................................................7

Nav Mesh Agent........................................................................................................................................................ 7

Change Animation State using Animator......................................................................................................8

Arrays Example Script...........................................................................................................................................9

Ray Cast Example Script.................................................................................................................................... 10

Three Scripts for Camera Follow, Mouse Orbit & Player Movement.............................................11

Page 2: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

1

Page 3: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

Move and Rotate an Object (using Transform.Translate & Transform.Rotate)

This script is attached to the Player. using UnityEngine;using System.Collections;

public class MoveRotate: MonoBehaviour {            void Start () {                  }                void Update () {            float moveX = Input.GetAxis ("Horizontal") / 10f;            float moveZ = Input.GetAxis ("Vertical") / 10f;            transform.Translate (moveX, 0, moveZ);//Remove moveX if you don’t want to move and roate at the same time

//Rotate on Y             if (Input.GetAxis ("Horizontal")<0)                {transform.Rotate(0f,-2,0f);}                         if (Input.GetAxis ("Horizontal")>0)                {transform.Rotate(0f,2,0f); }     }}

The Set Up

Create an object (e.g. Cube),  Give it a name.  Add a Rigid Body Component Either Turn Gravity off OR Create a floor using a plane or a flattened cube

TIP: Remove moveX if you don’t want to move and roate at the same time

Random Color

This script is attached to the object. Object Changes color when “Ctrl” is pressed

using UnityEngine;using System.Collections;

public class ChangeColour : MonoBehaviour{    void Start ()    {        gameObject.GetComponent<Renderer> ().material.color = new Color (Random.Range (0, 1f), Random.Range (0, 1f), Random.Range (0, 1f));    }     void Update ()    {        if (Input.GetButtonDown ("Fire1")) {            gameObject.GetComponent<Renderer> ().material.color = new Color (Random.Range (0, 1f), Random.Range (0, 1f), Random.Range (0, 1f));        }    }}

The Set Up

Create an object (e.g. Cube) Attach the script to the object  Press Ctrl to see color changing

Clamping (Mathf.Clamp)

This following script clamps the X & Y position of an object between 2 values

The Set Up

Create an object (e.g. Cube) Attach the script to the object 

2

Page 4: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

    void WeaponMovement(){        transform.Translate(new Vector3 (Input.GetAxis("Horizontal")/10,                                          Input.GetAxis("Vertical")/10,                                           -5));    //CLAMP IN X & Y        float xPos = transform.position.x + (Input.GetAxis("Horizontal"));        float yPos = transform.position.y + (Input.GetAxis("Vertical"));                transform.position = new Vector3 (Mathf.Clamp (xPos, -8f, 8f), Mathf.Clamp (yPos, -6f, 8f), 5f);

//INSTANTIATE & FIRE A CANONBALL- will need public RigidBody cannon declared above        if (Input.GetButtonUp ("Fire1")) {            Rigidbody canonball=Instantiate(cannon,firepoint.position,firepoint.rotation)                 as Rigidbody;            canonball.AddForce(transform.forward*canonSpeed);        }    }

Variables xPos and yPos keep track of the position and transform.position uses these valuses within a Mathf.Clamp method to limit the movement of the object

Change Levels (scenes) & Quit ApplicationThis script is attached to an Empty Game Object, which is dragged to the UI buttons

using UnityEngine;using System.Collections;

public class LevelChanger : MonoBehaviour{    public void ChangeLevel (string LevelName)    {        Application.LoadLevel (LevelName);    }    public void QuitGame ()    {        Application.Quit ();    }}

The Set Up

This script is attached to an Empty Game Object.  The Game Object is then dragged onto a UI Button.  Clicking on Functions will pop up a list, choose the script that holds the scene

changing code. Next choose the function name (in this case ChangeLevel). The public setting allows us to type the scene name in a small box that appears

on the bottom right.

TIP: Do not forget to add all scenes to ‘Build Settings’ otherwise the change level scripts won't work & quit wont work in edit mode

3

Page 5: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

Move, Jump and Rotate an Object (Rigidbody to move and prevent double jumps)

The script includes 2 methods to prevent double jump

using UnityEngine;using System.Collections;

public class MoveWithForce : MonoBehaviour {    float thrust=5f;    int jumpSpeed=150;    Rigidbody rb;    public GameObject myFloor;    //Ray & RayCast    private Ray myRay;    public Color rayColor;    RaycastHit objectHit;

    void Start() {        rb = GetComponent<Rigidbody>();    }    void FixedUpdate() {                     rb.MovePosition(transform.position + transform.forward * Time.deltaTime*Input.GetAxis("Vertical")*thrust);            if (Input.GetAxis ("Horizontal")<0)                transform.Rotate(0f,-2,0f);                  if (Input.GetAxis ("Horizontal")>0)                transform.Rotate(0f,2,0f);        Jump();    }    void Jump(){             /* //JUMP - CONTROLLING DOUBLE JUMP BY CHECKING DISTANCE FROM FLOOR - WORKS FINE         if(transform.position.y - myFloor.transform.position.y<2)        {            if(Input.GetButtonDown("Fire1"))            {                rb.AddForce(transform.up * jumpSpeed);            }        }        */        //CONTROL DOUBLE JUMP USING RAY CAST        Vector3 down = transform.TransformDirection(-Vector3.up) *2f;        myRay = new Ray (transform.position, down);        Debug.DrawRay(transform.position, down, Color.green);        Physics.Raycast(myRay,out objectHit, 2f);        if(objectHit.collider.tag=="floor")        {

Debug.Log("Jump");             if(Input.GetButtonDown("Fire1"))            {                rb.AddForce(transform.up * jumpSpeed);            }        }    }}

The Set Up

Select the Player (object) Add a Rigid Body Component Either Turn Gravity off OR Create a floor using a plane or a flattened cube

One method to control double jumps used here is to calculate the distance from the floor and only of the player is close to the floor, within a certain distance (in this case 2 units), can the Player Jump – see if statement

Another method is cast a Ray and see if the Ray has hit the floor. You can controkl the distance of the Ray being cast distance (in this case 2f units),

4

Page 6: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

Throw a Weapon (rigid body) – uses a timer to prevent rapid firing

This script can be embedded or attached to a player or the the weapon itself

using UnityEngine;using System.Collections;

public class ThrowWeapon : MonoBehaviour {    public Rigidbody weaponPrefab;    Rigidbody weapon;    public Transform weaponPos;    public float weaponSpeed=600.0f;    float myTime =1.0f;

    // Use this for initialization    void Start () {    }

    // Update is called once per frame    void FixedUpdate () {//Prevent Rapid Attacks using a Timer        myTime += Time.deltaTime;        if (Input.GetButtonDown ("Fire2")&&myTime>0.5f) {            Attack();  //calls method Attack            myTime = 0;        }    }

    void Attack()    {        weapon = Instantiate (weaponPrefab, weaponPos.position,weaponPos.rotation) as Rigidbody;        weapon.AddForce (weaponPos.transform.up * weaponSpeed);

    }}

The Set Up

Public variable weaponPrefab specifies the weapon to be instantiated This script can be attached to the player Public variable weaponSpeed can be adjusted for speed of thrown object Public Transform weaponPos is used to read the position (and perhaps

rotation) of the instantiated weapons. Drag and Drop an Empty GameObject here after placing the empty Object

exctaly where the weapon should be instantiated

The variables Rigidbody and Transform just extract the reigidbody component and the Transform component of the GameObject.

The timer myTime is initially set to a value 1.0f so that the player can fire without delay. But once the Attack() method is issued, the Timer is reset to 0 and the player must wait for myTime to be greater than (>) 0.5f; This prevents rapid firing and prevents the weapons from hitting each other

5

Page 7: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

Instantiating (spawning) using a for loop and Bouncy Material

This script is attached an Empty Game Object

using UnityEngine;using System.Collections;

public class MySpawner : MonoBehaviour{     public GameObject spawnObject1;     public GameObject spawnObject2;

Vector3 spawnPos; 

 void Start ()    {                     for (int i=0; i<=10; i++) {            spawnPos = new Vector3                 (Random.Range (-10f, 10f), 0f, Random.Range (-10f, 10f));            Instantiate (spawnObject1, spawnPos, Quaternion.identity);

            spawnPos = new Vector3                 (Random.Range (-10f, 10f), 0f, Random.Range (-10f, 10f));            Instantiate (spawnObject2, spawnPos, Quaternion.identity);        }    }}

Destroy or Reposition Instantiated ObjectsThis script is attached the prefabs being instantiated

void Update () {    if (transform.position.y < -10) {        Destroy (gameObject);

     // Destroy object (script above) or reposition using transform.position(script below)

  transform.position = new Vector3(Random.Range (-10f,10f),Random.Range (20f,40f),Random.Range (-10f,10f));    }    // gives it a new position in the same X-Z plane but different Y

The Set Up Create objects to be spawned Drag them into a folder called 'prefabs' Create an empty game object, rename it to GameScripts Create a new C# script and attach it to the empty game object called

gameScripts Once the "public" GameObjects are defined, they will appear in the properties

dialog box when the empty GameObject GameScripts is selected.  Drag and Drop the objects to be spawned into the empty fields, example shown

below

If the prefab objects have gravity turned on they will fall To get them to bounce off a plane or a floor- Add a 3D object Under Assets->Create->Physic Material, you can create an asset that imparts

collision properties to rigid bodies Set the friction and bounce of this asset and drag it and drop it under the

collider panel infront of the Material field for the object whose bounce you wish to set. (shown below)

To kill objects under certain conditions, attach a script with the Destroy(gameObject); cattach ode to the prefab

6

Page 8: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

7

Page 9: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

Binding UI elements to variablesThis script is attached the Player

TIP: Do not forget to - using UnityEngine.UI; - Line 3 in the code below

using UnityEngine;using System.Collections;using UnityEngine.UI;

public class MyHero : MonoBehaviour{    public string characterName;    public bool characterMoving;    public float characterPositionX;    public int characterHealth;    public int characterScore;    public Text txtName; //UI Text     public Text txtMoving;    public Text txtPosition;    public Slider sldHealth; // UI Slider    public Text txtScore;        void Start ()    {        txtName.text = characterName;         }        void Update ()    {  //Bind UI elements with variables, not some need to be converted to Text using ToString(); method

        txtMoving.text = characterMoving.ToString ();         txtPosition.text = characterPositionX.ToString ();        sldHealth.value = characterHealth;        txtScore.text = characterScore.ToString ();        

        float xMovement = Input.GetAxis ("Horizontal") / 10;        float yMovement = Input.GetAxis ("Vertical") / 10;        transform.Translate (xMovement, 0f, yMovement);                characterPositionX = transform.position.x;        if ((xMovement !=0 && yMovement !=0)) {            characterMoving = false;        } else {            characterMoving = true;        }    }}

The Set Up

Create the UI elements in a Canvas. - Text, Sliders, etc.

Set up public variables in the code for characterName, characterHealth, characterLife etc. using string, int, bool etc whatever is appropriate e.g.    public string characterName;    public bool characterMoving;    public float characterPositionX;    public int characterHealth;

TIP: Dont forget to add  using UnityEngine.UI; Now set up public variables using UI data types to receive the information from these

variables e.g.       txtMoving.text = characterMoving.ToString();        txtPosition.text = characterPositionX.ToString();        sldHealth.value = characterHealth;        txtScore.text = characterScore.ToString ();

After finishing up the script. Return to the inspector and drag and drop the UI elements to their corresponding UI variables 

One important step is to link the UI elements to the public variables in the GUI. See image below. Also, the same applies when one script reads variables of the other.(in next topic)

Triggers, Collisions & Importing Scripts and variablesThis script is attached the Player

The Set Up

A Player / Object (Hero) with a RigidBody component

8

Page 10: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

using UnityEngine;using System.Collections;

public class HeroHealth : MonoBehaviour{    public MyHero healthRef;     //this allows this script to refer to variables from myHero.cs        void OnCollisionEnter (Collision myObject)    {        if (myObject.gameObject.tag == "enemy") {            healthRef.characterScore -= 10;            healthRef.characterHealth -= 20;        }    }        void OnTriggerEnter (Collider myObject)    {        if (myObject.gameObject.tag == "health") {            healthRef.characterHealth += 20;            healthRef.characterScore += 10;            Destroy (myObject.transform.gameObject);        }    }}

Script attached to player An object with colliders (should have a collider component) An object marked as a trigger (see image below)

Nav Mesh Agent This script is attached to the enemy objects

using UnityEngine;using System.Collections;

public class Follow : MonoBehaviour{    private NavMeshAgent agent;    public GameObject getHim;    void Start ()    {        agent = GetComponent<NavMeshAgent> ();    }    void Update ()    {               agent.SetDestination (getHim.transform.position);            }}

The Set Up

Choose Surface on which enemies shall follow Player Go to WIndow->Navigation Choose Static Then Choose Bake tab and then hit the "Bake" button. Adjust step height, slopes etc to determine how the enemies respond

Choose the enemy (plane, dog, villain, whatever) Add a component called Nav Mesh Agent Adjust his speed, stopping distance etc Add the script on the left Drag and drop the hero into the public variable dialog box to set the object being chased

9

Page 11: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

Change Animation State using AnimatorThis script is attached to the player

public class PlayerMovement : MonoBehaviour{    //STEP 1 - Set Variable for animator component    private Animator animator;         // Use this for initialization    void Start ()    {        //STEP 2 - Get theAnimator  component. It should be attached to object        animator = GetComponent <Animator> ();     }        // Update is called once per frame    void Update ()    {        float fwd = Input.GetAxis ("Vertical") / 10f;        transform.Translate (0, 0, -fwd);        float rot = Input.GetAxis ("Horizontal");        transform.Rotate (0, rot, 0);        //STEP 3 - If statements to set the parameter isWalking true and False        if (fwd != 0 || rot != 0) {            animator.SetBool ("isWalking", true);        } else {            animator.SetBool ("isWalking", false);        }        // end if statement for animator    }}

The Set Up

PART 1

Import your Max file with Animations OS X wont import the Max file directly, you will need to do an FBX export. But a PC will import

directly Click on the animation, then click on "Edit" under the inspector and set the various animations

by clicking on add (plus sign +) Set the start frame, end frame and loop if needed (e.g. for walk)

PART 2

Right click on Assets and create an Animation Controller. If the Max file has attached an animator component, then drag this controller into the field which reads Animation Controller or just drag into the inspector when the Player is selected and an animator will be aded automatically.

Double click on the Animation Controller to open up the State Machine.  Drag and drop the various animation states into this Right click on the default state and set that as the default An arrow from entry to this state will appear On the left side, Choose Parameters and click on + to add a parameter like 'Bool'  and call it

'isWalking' On the right side right click on the idle state and choose create Transition, drag and drop to

the walking state. When you click on the arrow, on the right side you can set that this occurs when the parameter isWalking is true and you can add a second transition the other way round and set the isWalking to False

10

Page 12: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

Arrays Example ScriptAttach the script to an Empty Object.

using UnityEngine;using System.Collections;

public class MyArrayScript : MonoBehaviour {

    public GameObject[] objectToSpawn;

    void Start () {

            randomItem = Random.Range (0, objectToSpawn.Length);//gets a random number from 0 to array LengthInstantiate (objectToSpawn [randomItem], new Vector3 (0,0,0, Quaternion.identity);        }

The Set Up

Attach Script to an Empty Game Object Create a few prefab Objects Click on Emty Game Object. Click on triangle to Open Array Onject to Spawn Specify a number of objects Drag and Drop prefabs into the Array & Play

11

Page 13: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

Ray Cast Example ScriptAttach the script either a player or an enemy to detect.

using UnityEngine;using System.Collections;

public class RayCastDemo : MonoBehaviour {    private Ray myRay;    public Transform testIfHit; //This is a Sphere Object. Drag and Drop    public Color rayColor; //This is a Color. Remember to set Aplha to >0 e.g. 1

    RaycastHit objectHit;    public GameObject missile; //This is a prefab sword. Drag and Drop    public Transform missileSpawn; //This is a Empty Game oBject Indicating where the sword will instantiate     public int missileSpeed=100;    float myTime;    // Use this for initialization    void Start () {    }    // Update is called once per frame    void Update () {

        myRay = new Ray (transform.position,transform.forward*50);        Debug.DrawRay (transform.position,transform.forward*50, rayColor);

        Physics.Raycast(myRay,out objectHit, 10f);        if (objectHit.collider.tag=="HitHim") {            Debug.Log ("FIRE");            Attack ();            } else {            Debug.Log ("STOP FIRE");        }    }

    void Attack(){        GameObject clone=Instantiate (missile, missileSpawn.position, Quaternion.identity) as GameObject;        clone.GetComponent<Rigidbody>().AddForce (new Vector3 (0, 0, missileSpeed));        Destroy (clone, 5f);    }}

The Set Up

You basically need a player and an enemy. Attach the script to the Enemy You can drag and drop the player object into the public variable testIfHit;

TIP: I have attached swords (rectangular blocks as prefabs, that get intansiated when the Ray detects the player. I have just animated my Sphere, but you can get yours to move around

12

Page 14: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

Three Scripts for Camera Follow, Mouse Orbit & Player Movement

MatchRotation.cs

using UnityEngine;using System.Collections;public class MatchRotation : MonoBehaviour {    public GameObject objectToMatchRotationWith;    void Update()    {        transform.rotation = objectToMatchRotationWith.transform.rotation;    }}

The Set Up

Create a Hierarchy of Game Objects as shown below:

o Camera (holds Script MouseOrbit.cs)o PlayerHolder (holds Script Player.cs)

Player AimHere (holds Script MatchRotation.cs) Sword Shield etc

Select Camera - Drag and Drop GameObject AimHere into public Transform Target)Select PlayerHolder - Drag and Drop GameObject AimHere into public PlayergraphicSelect AimHere - Drag and Drop GameObject Camera into public ObjectToMatchRotation

Player.cs

using UnityEngine;using System.Collections;public class Player : MonoBehaviour{    public float speed = 2f;    public Transform playergraphic;    public GameObject camera;    void Update()   {     Movement();  }

    void Movement()        //Player object movement    {        float horMovement = Input.GetAxisRaw("Horizontal");        float vertMovement = Input.GetAxisRaw("Vertical");        if (horMovement != 0 && vertMovement != 0)        {            speed = 3f;        }        else        {            speed = 2f;        }transform.Translate(camera.transform.right * horMovement * Time.deltaTime * speed);transform.Translate(camera.transform.forward * vertMovement * Time.deltaTime * speed);        //These two Vector3's are needed to keep the player from rotating into the ground        Vector3 forwardOnlyXandZ = new Vector3            (            camera.transform.forward.x * Input.GetAxis("Vertical"),            0,            camera.transform.forward.x * Input.GetAxis("Vertical"));        Vector3 rightOnlyXandZ = new Vector3            (             camera.transform.right.z * Input.GetAxis("Horizontal"),             0,

// -------- > Script continues here //Player graphic rotation ---         //Vector3 moveDirection = new Vector3(horMovement, 0, vertMovement);        Vector3 moveDirection = forwardOnlyXandZ + rightOnlyXandZ;

        if (moveDirection != Vector3.zero)        {            Quaternion newRotation = Quaternion.LookRotation(moveDirection);            playergraphic.transform.rotation =                                             Quaternion.Slerp(                                            playergraphic.transform.rotation,                                             newRotation,                                            Time.deltaTime * 8);        }//END HERE... unless using animations         //Player graphic animation               //SET BOOL TO SWITCH ANIMATIONS FOR MOVEMENT        /* if (moveDirection.magnitude > 0.05f)        {            playergraphic.GetComponent<Animator>().SetBool("isWalking", true);         }        else        {            playergraphic.GetComponent<Animator>().SetBool("isWalking", false);        } */    }}

13

Page 15: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

             camera.transform.right.z * Input.GetAxis("Horizontal") );                //SCRIPT continues on right side ----------MouseOrbit.cs

using UnityEngine;using System.Collections;/// <summary>/// Modified from: http://wiki.unity3d.com/index.php?title=MouseOrbitImproved/// </summary>public class MouseOrbitImproved : MonoBehaviour{    public Transform target;    float distance;    public float xSpeed = 120.0f;    public float ySpeed = 120.0f;

    public float yMinLimit = -20f;    public float yMaxLimit = 80f;

    public float distanceMin = 0.5f;    public float distanceMax = 15f;

    float x = 0.0f;    float y = 0.0f;

    public float cameraDistance = 5f;    // Use this for initialization    void Start()    {        Vector3 angles = transform.eulerAngles;        x = angles.y;        y = angles.x;        distance = cameraDistance;    }

    void Update()    {        if (target)        {            x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;            y = ClampAngle(y, yMinLimit, yMaxLimit);            Quaternion rotation = Quaternion.Euler(y, x, 0);            distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * 5, distanceMin, distanceMax);            //A ray out from the target towards the camera to see             Ray forwardRay = new Ray(target.position, -transform.forward * cameraDistance);            //Draw the ray for debugging - not necessary            Debug.DrawRay(target.position, -transform.forward * cameraDistance);            //Cast the ray to see if it's hitting an object and store the HIT details           //SCRIPT continues on right side ----------

// -------- > Script continues here  RaycastHit hit;            Physics.Raycast(forwardRay, out hit, distance);            //Cast a ray the distance the camera should be and if hitting an object use the            //distance of HIT from the above raycast to determine where the camera should be           if(Physics.Raycast(forwardRay, cameraDistance))               {                    distance -= hit.distance / 20f;            }            else            {                if (distance < cameraDistance)                {                    distance += 0.1f;                }            }            Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);            Vector3 position = rotation * negDistance + target.position;            transform.rotation = rotation;            transform.position = position;        }    }

    public static float ClampAngle(float angle, float min, float max)    {        if (angle < -360F) { angle += 360F; }        if (angle > 360F) { angle -= 360F; }        return Mathf.Clamp(angle, min, max);    }}

14

Page 16: :: Dileep's Web :: - Move and Rotate an Object (using ...dileepsweb.weebly.com/.../4/6/5/8/4658996/csharpquic… · Web viewC# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part

15