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



C# for UNITY3d: Sem 1a.k.a. The Gospel of Mark – Part 1Special Thanks to Mark Hoey, whose lectures this booklet is based onTABLE OF CONTENTS TOC \o "1-1" Move and Rotate an Object (using Transform.Translate & Transform.Rotate) PAGEREF _Toc293298722 \h 1Random Color PAGEREF _Toc293298723 \h 1Clamping (Mathf.Clamp) PAGEREF _Toc293298724 \h 2Change Levels (scenes) & Quit Application PAGEREF _Toc293298725 \h 2Move, Jump and Rotate an Object (Rigidbody to move and prevent double jumps) PAGEREF _Toc293298726 \h 3Throw a Weapon (rigid body) – uses a timer to prevent rapid firing PAGEREF _Toc293298727 \h 4Instantiating (spawning) using a for loop and Bouncy Material PAGEREF _Toc293298728 \h 5Destroy or Reposition Instantiated Objects PAGEREF _Toc293298729 \h 5Binding UI elements to variables PAGEREF _Toc293298730 \h 6Triggers, Collisions & Importing Scripts and variables PAGEREF _Toc293298731 \h 7Nav Mesh Agent PAGEREF _Toc293298732 \h 7Change Animation State using Animator PAGEREF _Toc293298733 \h 8Arrays Example Script PAGEREF _Toc293298734 \h 9Ray Cast Example Script PAGEREF _Toc293298735 \h 10Three Scripts for Camera Follow, Mouse Orbit & Player Movement PAGEREF _Toc293298736 \h 11Move 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 UpCreate an object (e.g. Cube),?Give it a name.?Add a Rigid Body ComponentEither Turn Gravity off ORCreate a floor using a plane or a flattened cubeTIP: Remove moveX if you don’t want to move and roate at the same timeRandom ColorThis script is attached to the object. Object Changes color when “Ctrl” is pressedusing?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 UpCreate an object (e.g. Cube)Attach the script to the object?Press Ctrl to see color changingClamping (Mathf.Clamp)This following script clamps the X & Y position of an object between 2 values????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);????????}????}The Set UpCreate an object (e.g. Cube)Attach the script to the object?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 objectChange Levels (scenes) & Quit ApplicationThis script is attached to an Empty Game Object, which is dragged to the UI buttonsusing?UnityEngine;using?System.Collections;public?class?LevelChanger?:?MonoBehaviour{????public?void?ChangeLevel?(string?LevelName)????{????????Application.LoadLevel?(LevelName);????}????public?void?QuitGame?()????{????????Application.Quit?();????}}The Set UpThis 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 modeMove, Jump and Rotate an Object (Rigidbody to move and prevent double jumps)The script includes 2 methods to prevent double jumpusing?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 UpSelect the Player (object)Add a Rigid Body ComponentEither Turn Gravity off ORCreate a floor using a plane or a flattened cubeOne 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 statementAnother 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), Throw a Weapon (rigid body) – uses a timer to prevent rapid firingThis 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 UpPublic variable weaponPrefab specifies the weapon to be instantiatedThis script can be attached to the player Public variable weaponSpeed can be adjusted for speed of thrown objectPublic 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 instantiatedThe 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 Instantiating (spawning) using a for loop and Bouncy MaterialThis script is attached an Empty Game Objectusing?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 instantiatedvoid?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 YThe Set UpCreate objects to be spawnedDrag them into a folder called 'prefabs'Create an empty game object, rename it to GameScriptsCreate a new C# script and attach it to the empty game object called gameScriptsOnce 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 belowIf the prefab objects have gravity turned on they will fallTo get them to bounce off a plane or a floor- Add a 3D objectUnder Assets->Create->Physic Material, you can create an asset that imparts collision properties to rigid bodiesSet 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 prefabBinding UI elements to variablesThis script is attached the PlayerTIP: Do not forget to - using UnityEngine.UI; - Line 3 in the code belowusing?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 UpCreate 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 Playerusing?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);????????}????}}The Set UpA Player / Object (Hero) with a RigidBody componentScript attached to playerAn 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 objectsusing?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 UpChoose Surface on which enemies shall follow PlayerGo to WIndow->NavigationChoose StaticThen Choose Bake tab and then hit the "Bake" button.Adjust step height, slopes etc to determine how the enemies respondChoose the enemy (plane, dog,?villain, whatever)Add a component called Nav Mesh AgentAdjust his speed, stopping distance etcAdd the script on the leftDrag and drop the hero into the public variable dialog box to set the object being chasedChange Animation State using AnimatorThis script is attached to the playerpublic?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 UpPART 1Import your Max file with?AnimationsOS X wont?import?the Max file directly, you will need to do an FBX export.?But a PC will import directlyClick 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 2Right 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 thisRight click on the default state and set that as the defaultAn arrow from entry to this state will appearOn 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 FalseArrays 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 UpAttach Script to an Empty Game ObjectCreate a few prefab ObjectsClick on Emty Game Object.Click on triangle to Open Array Onject to SpawnSpecify a number of objectsDrag and Drop prefabs into the Array & PlayRay 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 UpYou basically need a player and an enemy. Attach the script to the EnemyYou 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 aroundThree Scripts for Camera Follow, Mouse Orbit & Player MovementMatchRotation.csusing?UnityEngine;using?System.Collections;public?class?MatchRotation?:?MonoBehaviour?{????public?GameObject?objectToMatchRotationWith;????void?Update()????{????????transform.rotation?=?objectToMatchRotationWith.transform.rotation;????}}The Set UpCreate a Hierarchy of Game Objects as shown below:Camera (holds Script MouseOrbit.cs)PlayerHolder (holds Script Player.cs)PlayerAimHere (holds Script MatchRotation.cs)SwordShield etcSelect 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 ObjectToMatchRotationPlayer.csusing?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,?????????????camera.transform.right.z?*?Input.GetAxis("Horizontal")?);????????????????//SCRIPT continues on right side ---------- // -------- > 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);????????}?*/????}}MouseOrbit.csusing?UnityEngine;using?System.Collections;///?<summary>///?Modified?from:?{????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);????}} ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download