I need advice on how to create a system in unity that finds the distance between one object (the player) and multiple others, determines which of those objects is closest, and then returns the value of that closest object as a float.
If you only know how to do one or two of these, it’ll still help.
Depends, are the objects in question known at all times? What’s this going to be used for?
This is going to be used for a rhythm game, and yes, the objects’ position will be contsant
A rhythm game, so this is going to be for point giving on accuracy, like how close the “note” is to the “bar”?
If that is the case, I would use collision for the “bar” to detect the object, and use Vector3.magnitude when the player hits the key to get the distance the “note” is from the “bar”.
something like this:
//this snipplet is supposed to be somewhere on the main script of the "bar"
private Transform note;
private float distance;
void Update(){
if(Input.GetKeyDown(Keycode.*your key*)){
distance = (note.position - transform.position).magnitude;
}
}
void OnTriggerEnter(Collider col){
note = col.transform;
}
what wrong with Vector3.Distance?
@Laperen Thanks so much, this worked!
nothing, there is virtually no difference between using .Distance and .magnitude, just a matter of preference. But you can simply switch out .magnitude for .sqrMagnitude for efficiency sake if you are doing simple comparison, although for @Balistic_penguin 's case precision is needed.
just take note of when the collision goes over the bar, since magnitude does not give a damn about the direction of said magnitude. you can play around with offsetting the collision, or if your game is axis locked, use the axis value for comparison instead of the Vector3 position of the objects.