- Home /
Hop from transform to transform in 2D game?
Hi there, I have an array of transforms scattered around my scene, and I want my player to be able to move by jumping from one to the next (next meaning closest), in whichever direction they input. In the following function, I was able to get my guy to go from closest point to closest point, but I can't seem to figure out how to incorporate direction into it:
Vector3 FindClosestPoint(Vector2 movementDirection)
{
Vector3 currentPosition = transform.position;
Transform closestPoint = null;
float distanceToClosestPoint = Mathf.Infinity;
for (int i = 0; i < points.Length; i++)
{
Vector3 pointDirection = points[i].position - currentPosition;
float pointAngle = Vector2.Angle(pointDirection, movementDirection);
float distanceToPoint = Vector2.Distance(points[i].position, currentPosition);
if (distanceToPoint < distanceToClosestPoint)
{
if (pointAngle < 90) // this is where I think my biggest logic error is
closestPoint = points[i];
distanceToClosestPoint = distanceToPoint;
}
}
return closestPoint.position;
}
The Vector2 param passed in is either Vector2.up, down, left, or right. I get a null reference exception when my "if (pointAngle < 90)" doesn't find anything - that if statement doesn't behave like I expect it to, instead of checking whether the angle between the direction I pass in and the direction of the target point is within my player's hardcoded 90 degree "cone of vision," it seems to be doing something else. I can never really predict which transform the player will jump to.
The first response in this forum is very close to what I have implemented, $$anonymous$$us the directional bit I'm trying to do:
http://forum.unity3d.com/threads/clean-est-way-to-find-nearest-object-of-many-c.44315/
Your answer
Follow this Question
Related Questions
How to compare several distances? 1 Answer
Top-Down Enemy Ai Animation 0 Answers
How can I raycast the direction my 2D character is facing? 1 Answer
[2D] Object at X distance to Y direction from point 1 Answer
Get distance between 2 gameObjects? 2 Answers