FindingClosestObject

Author: Lars-Erik Jakobsson (save)

Description

This script illustrates how to find the closest transform to another transform. Commonly used to check which object is closest to the player. Should be ready to go for mobile devices too.

Usage

Name this script ClosestCollider.js and assign it to the player transform. From Inspector tweak the radius, masked layers and update frequency.

JavaScript - ClosestCollider.js

#pragma strict
#pragma downcast
import System;
 
/*
    ClosestCollider.js
    Description: Finding closest collider without using a pool
    Last updated: 2012-12-28
    Author: save
*/
 
var sphereRadius : float = 10.0; //Radius of the OverlapSphere
var sphereMask : LayerMask; //What layers the OverlapSphere sees
var updateFrequency : float = 1.0; //Update frequency of FindClosestCollider-function
 
private var cachedUF : float; //Cached value of updateFrequency
static var pTransform : Transform; //Cache the Player Transform
 
function Start () {
    pTransform = transform;
    RestartInvokeRepeating();
}
 
//Finding the closest collider
function FindClosestCollider () {
    if (updateFrequency!=cachedUF) RestartInvokeRepeating();
    var pSphere : Collider[] = Physics.OverlapSphere(pTransform.position, sphereRadius, sphereMask);
    if (pSphere==null||pSphere.Length==0) return;
    System.Array.Sort(pSphere, new PositionSorter());
    DoSomethingWithClosestTransform(pSphere[0].transform);
}
 
//Do something with the closest transform, for instance print its name in Console
function DoSomethingWithClosestTransform (t : Transform) {
    Debug.Log(t.name);
}
 
//This is just a fancy extra if you want to update the frequency in play mode
function RestartInvokeRepeating () {
    updateFrequency = Mathf.Clamp(updateFrequency, .01, 10.0);
    CancelInvoke("FindClosestCollider");
    InvokeRepeating("FindClosestCollider", .0, updateFrequency);
    cachedUF = updateFrequency;
}
 
 
//Sort the closest transform
class PositionSorter implements IComparer {
    function Compare(a : System.Object, b : System.Object) : int {
        if ( !(a instanceof Collider) || !(b instanceof Collider)) return;
        var posA : Collider = a;
        var posB : Collider = b;
        return (ClosestCollider.pTransform.position-posA.transform.position).magnitude.CompareTo((ClosestCollider.pTransform.position-posB.transform.position).magnitude);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值