- Home /
Question by
Josepht45 · Oct 28, 2014 at 11:11 PM ·
transform3dtagmovetowards
How can I make the nearest astroid move to my preset location?
In the code I have it finding the nearest object with the "Astroid" tag and when I hit the Fire3 key, it SHOULD move to the location transform which is directly in front of my player as a child object. But when ever I hit the 'C' key (Fire3), it just makes the nearest astroid disappear! So I'm pretty sure it's finding the closest astroid, but I still need to make it lock to the location transform position. Here's the code: using UnityEngine; using System.Collections;
public class AstroidFind : MonoBehaviour {
private GameObject[] gos;
private float distance;
private GameObject closest;
public Transform location;
public float speed;
void Update() {
float step = speed * Time.deltaTime;
gos = GameObject.FindGameObjectsWithTag ("Astroid");
distance = Mathf.Infinity;
foreach (GameObject go in gos)
{
Vector3 diff = go.transform.position - transform.position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
print ("Found Closest Astroid!");
}
}
if (Input.GetButtonDown ("Fire3"))
{
closest.transform.position = Vector3.MoveTowards (transform.position, location.position, step);
}
}
}
If anyone can help me it would be greatly appreciated!
Comment
Original code:
closest.transform.position = Vector3.$$anonymous$$oveTowards (transform.position, location.position, step);
Proposed code:
closest.transform.position = Vector3.$$anonymous$$oveTowards (closest.transform.position, transform.position, step);
I don't know what location.transform is; it looks like it might just be a local copy of the transform...?
Your answer
![](https://koobas.hobune.stream/wayback/20220613170206im_/https://answers.unity.com/themes/thub/images/avi.jpg)