- Home /
How to find closest object with matching y position?
Hello, I've been trying to create a player movement similar to that of an old Japanese sfc game called Daruma Dojo. The movement pattern has the player moving freely on the y axis, however the players x axis is 1 unit away from the closest block with the same y axis as the player. How would I find the closest object with matching y axis coordinates? Also, I won't be able to use tags as I need the tags for a system of detecting matching blocks. Any help would be great as I am still a beginner.
Hello.
Just need to have all blocks in a list when commencing the level.
then use a foreach function to check all blocks and see which matches,
Answer by ShadyProductions · Mar 12, 2020 at 11:08 AM
I suggest you keep all those 'blocks' in a list, and then you can search through the list using this algorithm:
private GameObject GetClosestGameObjectWithSameYAxis(GameObject source)
{
// comparing floating points with equal isn't always very correct because floats can become inaccurate, hence the tolerance
var tolerance = 0.01f;
// _blocks will be your list of game objects
var blocks = _blocks.Where(a => Math.Abs(a.transform.position.y - source.transform.position.y) < tolerance).ToList();
GameObject closest = null;
float closestDistance = float.MaxValue;
foreach (var block in blocks)
{
var distance = Vector3.Distance(source.transform.position, block.transform.position);
if (distance < closestDistance)
{
closest = block;
closestDistance = distance;
}
}
return closest;
}
Your answer
Follow this Question
Related Questions
How can i detect, that object is close to some coordinates? 1 Answer
How to program a bunch of 1st person animations at different speeds? 0 Answers
find the highest gameobject of stacked gameobjects 1 Answer
check if two colliders Rub against each other 1 Answer
Any way I can add rolling to this movement script that is similar to dark souls? 0 Answers