Search Unity

Chopping Tree Script

Discussion in 'Scripting' started by Frientor, Feb 14, 2016.

  1. Frientor

    Frientor

    Joined:
    Oct 5, 2013
    Posts:
    47
    Hello
    How do I put this javascript
    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var treeHealth : int = 5;
    4.  
    5. var logs : Transform;
    6. var coconut : Transform;
    7. var tree : GameObject;
    8.  
    9. var speed : int = 8;
    10.  
    11. function Start()
    12. {
    13.     tree = this.gameObject;
    14.     GetComponent.<Rigidbody>().isKinematic = true;
    15. }
    16.  
    17. function Update()
    18. {
    19.     if(treeHealth <= 0)
    20.     {
    21.         GetComponent.<Rigidbody>().isKinematic = false;
    22.         GetComponent.<Rigidbody>().AddForce(transform.forward * speed);
    23.         DestroyTree();
    24.     }
    25. }
    26.  
    27. function DestroyTree()
    28. {
    29.     yield WaitForSeconds(7);
    30.  
    31.    
    32.     var position : Vector3 = Vector3(Random.Range(-1.0, 1.0), 0, Random.Range(-1.0, 1.0));
    33.     Instantiate(logs, tree.transform.position + Vector3(0,0,0) + position, Quaternion.identity);
    34.     Instantiate(logs, tree.transform.position + Vector3(2,2,0) + position, Quaternion.identity);
    35.     Instantiate(logs, tree.transform.position + Vector3(5,5,0) + position, Quaternion.identity);
    36.    
    37.     Instantiate(coconut, tree.transform.position + Vector3(0,0,0) + position, Quaternion.identity);
    38.     Instantiate(coconut, tree.transform.position + Vector3(2,2,0) + position, Quaternion.identity);
    39.     Instantiate(coconut, tree.transform.position + Vector3(5,5,0) + position, Quaternion.identity);
    40.    
    41. }
    42.  
    43.  
    44.  
    45.  
    to C# script
    Code (CSharp):
    1. using System.Collections.Generic;
    2. using UnityEngine;
    3.  
    4. public class PickaxeChop : MonoBehaviour
    5. {
    6.     public int ChopPower;
    7.     public GameObject ChoppingWoodChips;
    8.     public GameObject[] FallingTreePrefab;
    9.     public GameObject[] TreeOnTheGroundPrefab;
    10.     public GameObject Impact;
    11.  
    12.  
    13.     private int m_ChopDamage;
    14.     private int m_ChopDamage2;
    15.     private int m_CurrentChoppingTreeIndex = -1;
    16.     // Use this for initialization
    17.     private void Start()
    18.     {
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     private void Update()
    23.     {
    24.         if (Input.GetMouseButton(0))
    25.         {
    26.             GetComponent<Animation>().Play("PickAnimation");
    27.         }
    28.     }
    29.  
    30.     public void TreeChop()
    31.     {
    32.         // Did we click/attack something?
    33.  
    34.         RaycastHit hit;
    35.         // This ray will see what is where we clicked er chopped
    36.         var impactOnScreenPosition = Camera.main.WorldToScreenPoint(Impact.transform.position);
    37.  
    38.         Ray ray = Camera.main.ScreenPointToRay(impactOnScreenPosition);
    39.            
    40.  
    41.         // Did we hit anything within 10 units?);)
    42.         if (Physics.Raycast(ray, out hit, 10.0f))
    43.         {
    44.             // Did we even click er chop on the terrain/tree?);
    45.             if (hit.collider.name != Terrain.activeTerrain.name)
    46.             {
    47.                 // We didn't hit any part of the terrain (like a tree)
    48.                 return;
    49.             }
    50.  
    51.             // We hit the "terrain"! Now, how high is the ground at that point?
    52.             float sampleHeight = Terrain.activeTerrain.SampleHeight(hit.point);
    53.  
    54.             // If the height of the exact point we clicked/chopped at or below ground level, all we did
    55.             // was chop dirt.
    56.             if (hit.point.y <= sampleHeight + 0.01f)
    57.             {
    58.                 return;
    59.             }
    60.             // We must have clicked a tree! Chop it.
    61.             // Get the tree prototype index we hit, also.
    62.             int protoTypeIndex = ChopTree(hit);
    63.             if (protoTypeIndex == -1)
    64.             {
    65.                 // We haven't chopped enough for it to fall.
    66.                 return;
    67.             }
    68.             GameObject protoTypePrefab = Terrain.activeTerrain.terrainData.treePrototypes[protoTypeIndex].prefab;
    69.            
    70.             var fallenTreeScript = protoTypePrefab.GetComponent<FallenTree>();
    71.         }
    72.     }
    73.  
    74.     // Chops down the tree at hit location, and returns the prototype index
    75.     // With some changes, this could be refactored to return the selected (or chopped) tree, and
    76.     // then either display tree data to the player, or chop it.
    77.     // The return value is the tree slot index of the tree, it is -1 if we haven't chopped the tree down yet.
    78.     private int ChopTree(RaycastHit hit)
    79.     {
    80.         TerrainData terrain = Terrain.activeTerrain.terrainData;
    81.         TreeInstance[] treeInstances = terrain.treeInstances;
    82.  
    83.         // Our current closest tree initializes to far away
    84.         float maxDistance = float.MaxValue;
    85.         // Track our closest tree's position
    86.         var closestTreePosition = new Vector3();
    87.         // Let's find the closest tree to the place we chopped and hit something
    88.         int closestTreeIndex = 0;
    89.         var closestTree = new TreeInstance();
    90.         for (int i = 0; i < treeInstances.Length; i++)
    91.         {
    92.             TreeInstance currentTree = treeInstances[i];
    93.             // The the actual world position of the current tree we are checking
    94.             Vector3 currentTreeWorldPosition = Vector3.Scale(currentTree.position, terrain.size) +
    95.                                                Terrain.activeTerrain.transform.position;
    96.  
    97.             // Find the distance between the current tree and whatever we hit when chopping
    98.             float distance = Vector3.Distance(currentTreeWorldPosition, hit.point);
    99.  
    100.             // Is this tree even closer?
    101.             if (distance < maxDistance)
    102.             {
    103.                 maxDistance = distance;
    104.                 closestTreeIndex = i;
    105.                 closestTreePosition = currentTreeWorldPosition;
    106.                 closestTree = currentTree;
    107.             }
    108.         }
    109.  
    110.         // get the index of the closest tree..in the terrain tree slots, not the index of the tree in the whole terrain
    111.         int prototypeIndex = closestTree.prototypeIndex;
    112.  
    113.         // Play our chop shound
    114.         PlayChopSound(hit.point);
    115.  
    116.         if (m_CurrentChoppingTreeIndex != closestTreeIndex)
    117.         {
    118.             //This is a different tree we are chopping now, reset the damage!
    119.             // This means we can only chop on one tree at a time, switching trees sets their
    120.             // health back to full.
    121.             m_ChopDamage = ChopPower;
    122.             m_ChopDamage2 = ChopPower;
    123.             m_CurrentChoppingTreeIndex = closestTreeIndex;
    124.         }
    125.         else
    126.         {
    127.             // We are chopping on the same tree.
    128.             m_ChopDamage += ChopPower;
    129.             m_ChopDamage2 += ChopPower;
    130.         }
    131.  
    132.        
    133.      if (m_ChopDamage >= 100)
    134.             {
    135.                 var treeInstancesToRemove = new List<TreeInstance>(terrain.treeInstances);
    136.                 // We have chopped down this tree!
    137.                 // Remove the tree from the terrain tree list
    138.                 treeInstancesToRemove.RemoveAt(closestTreeIndex);
    139.                 terrain.treeInstances = treeInstancesToRemove.ToArray();
    140.                 // Now refresh the terrain, getting rid of the darn collider
    141.                 float[,] heights = terrain.GetHeights(0, 0, 0, 0);
    142.                 terrain.SetHeights(0, 0, heights);
    143.                 // Put a falling tree in its place, tilted slightly away from the player
    144.                 var fallingTree =
    145.                     (GameObject)
    146.                     Instantiate(FallingTreePrefab[prototypeIndex], closestTreePosition,
    147.                                 Quaternion.AngleAxis(2, Vector3.right));
    148.                 fallingTree.transform.localScale = new Vector3(closestTree.widthScale * fallingTree.transform.localScale.x,
    149.                                                                closestTree.heightScale * fallingTree.transform.localScale.y,
    150.                                                                closestTree.widthScale * fallingTree.transform.localScale.z);
    151.             }
    152.             return prototypeIndex;
    153.        
    154.    
    155.      if    (m_ChopDamage2 >= 100) {
    156.                 var treeInstancesToRemove = new List<TreeInstance>(terrain.treeInstances);
    157.                 // We have chopped down this tree to get logs!
    158.                 // Remove the tree from the terrain tree list
    159.                 treeInstancesToRemove.RemoveAt(closestTreeIndex);
    160.                 terrain.treeInstances = treeInstancesToRemove.ToArray();
    161.                 // Now refresh the terrain, getting rid of the darn collider
    162.                 float[,] heights = terrain.GetHeights(0, 0, 0, 0);
    163.                 terrain.SetHeights(0, 0, heights);
    164.                 // Put a trunk in its place after falling tree chopped down
    165.                 var TreeOnTheGround =
    166.                     (GameObject)
    167.                 Instantiate(TreeOnTheGroundPrefab[prototypeIndex], closestTreePosition,
    168.                                 Quaternion.AngleAxis(2, Vector3.right));
    169.             TreeOnTheGround.transform.localScale = new Vector3(closestTree.widthScale * TreeOnTheGround.transform.localScale.x,
    170.                                                                closestTree.heightScale * TreeOnTheGround.transform.localScale.y,
    171.                                                                closestTree.widthScale * TreeOnTheGround.transform.localScale.z);
    172.             }
    173.             return prototypeIndex;
    174.         }
    175.  
    176.  
    177.     private void PlayChopSound(Vector3 point)
    178.     {
    179.         Instantiate(ChoppingWoodChips, point, Quaternion.identity);
    180.     }
    181. }
    so that it was like in this video