- Home /
How can I compare a Distance i measured using Vector3.Distance with a number
I am attempting to code an AI system for a game I am making and I wanted to do so without using waypoints or navmesh (purely dynamic). However when I try to code a statement for detecting how close the AI is to a wall or object I get the statement Operator '<' cannot be used with a left hand side of type 'UnityEngine.Vector3' and a right hand side of type 'int'. How can I get this to work?
if ((hit.transform.tag == "Obstacle") && (hit.point - transform.position) < 2) {
do something
}
Answer by robertbu · Jul 02, 2013 at 05:26 PM
Two ways:
(hit.point - transform.position).magnitude < 2.0
Or:
Vector3.Distance(hit.point - transform.position) < 2.0
Answer by bigbat · Jul 02, 2013 at 05:48 PM
According to robertbu answer,if you want exactly compre distance with an int number you must typecat it. like this snippet:
.
.//your variable declaration
public int desiredistance=2;
private float disttoobj;
//put this line of code where you want compare distance
disttoobj=Vector3.Distance(hit.point , transform.position);
if((int)disttoobj < desiredistance)
{
//do something here
}
Best method is this case is to use '2.0' ins$$anonymous$$d of '2' so the compiler knows it is a float, but that does not solve his problem. If he gets the distance formula right, the compiler (Javascript and C#) will correctly cast the '2' without an explicit cast. And the form of casting you are doing here only works in C#.
...you don't need to cast the float
to an int
to compare them, the int
will be implicitly cast to a float
. Try it.
Your answer
Follow this Question
Related Questions
collision detection fail 1 Answer
2D Collision 1 Answer
Collision detection of certain ojects 1 Answer
pushing object 2 Answers