I once came upon an idea on the forums for tree colliders. Why not use 1 single collider for trees. This Collider would move to the nearest tree from the player’s position. So I scripted something together and got some result.
My Collider moves to the nearest tree, once. When I start the game, the collider is on the nearest tree, but it doesn’t update, so I guess I have a logic mistake somewhere in my script. If someone could look over it and tell me where I made a mistake. I use LateUpdate() to make sure the character has made his move, but even in Update() it’s not working. Thanks for the help. I also would be happy for optimization. I’m not the greatest scripter, I try though.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TreeCollider : MonoBehaviour
{
TreeInstance[] trees;
TreeInstance tree;
Vector3 treePos;
Vector3 pos;
// Terrain Size
Vector3 ts;
//Terrain Position
Vector3 tp;
//How far is the nearest tree
float proximity;
float nearestTree = 10000f;
//Player Position
Vector3 player;
int nearest;
//moveable Collider
GameObject treeCollider;
private void Start()
{
//Find all trees on terrain
trees = Terrain.activeTerrain.terrainData.treeInstances;
//assign terrain size
ts = Terrain.activeTerrain.terrainData.size;
//assign terrain position
tp = Terrain.activeTerrain.transform.position;
//find the player position
player = GameObject.FindGameObjectWithTag("Player").transform.position;
//find the collider in the Hierarchy
treeCollider = GameObject.Find("TreeCollider");
}
private void LateUpdate()
{
//go through every tree on terrain and check how far it is from player
for (int i = 0; i < trees.Length; i++)
{
tree = trees[i];
treePos = tree.position;
//find the world coordinates
pos = (Vector3.Scale(ts, treePos) + tp);
proximity = (player - pos).sqrMagnitude;
if (proximity < nearestTree)
{
nearestTree = proximity;
nearest = i;
}
}
//assign nearest tree
tree = trees[nearest];
treePos = tree.position;
pos = (Vector3.Scale(ts, treePos) + tp);
//move the collider to the nearest tree position
treeCollider.transform.position = pos;
}
}