Luke0
September 17, 2017, 8:35am
1
Hi I’ve spent forever trying to figure out this problem.
I need a cube to move towards the nearest object which has a specific tag “Collis”. From there on collison, that objects tag will be changed to “dead” and the cube will move to the next object.
I’ve looked through multiple other similar questions but their code just doesn’t work!
Can someone help!
Thx
Hellium
September 17, 2017, 10:52am
2
Don’t forget :
The object holding the script must have a Collider and Rigidbody set to non-kinematic
The objects with the tag Collis
must have a Collider
using UnityEngine;
public class Chaser : MonoBehaviour
{
public float speed = 1 ;
private Transform target ;
private Rigidbody rb ;
private void Start()
{
target = FindTarget();
rb = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
if( target != null )
{
Vector3 direction = (target.position - transform.position).normalized;
rb.MovePosition(transform.position + direction * speed * Time.deltaTime);
}
}
private void OnCollisionEnter( Collision collision )
{
if( collision.collider.CompareTag("Collis") )
{
collision.collider.gameObject.tag = "Untagged"; // Remove the tag so that FindTarget won't return it
Destroy( collision.collider.gameObject ) ;
target = FindTarget();
}
}
public Transform FindTarget()
{
GameObject[] candidates = GameObject.FindGameObjectsWithTag("Collis");
float minDistance = Mathf.Infinity;
Transform closest ;
if ( candidates.Length == 0 )
return null;
closest = candidates[0].transform;
for ( int i = 1 ; i < candidates.Length ; ++i )
{
float distance = (candidates*.transform.position - transform.position).sqrMagnitude;*
if ( distance < minDistance )
{
closest = candidates*.transform;*
minDistance = distance;
}
}
return closest;
}
}
Luke0
September 30, 2017, 11:17pm
3
wow, your amazing!! THANKS!!!