- Home /
Check if an object is at a relative position?
Is there a javascript function where a object checks if another object (or tag) is at a certain position relative to itself, and then if so does a certain action?
For example, when a corridor segment is created, it checks if there is a segment in front (say 20m) of it. If there is, it will either turn left or right. The same applies if there is a segment to its left, it will go straight or right, etc.
Answer by clunk47 · Jan 01, 2013 at 08:46 PM
You could try either Physics.Raycast, or Vector3.Distance.
Thanks, but I don't think they would be able to differentiate between when somethings to your left or right, they only return the distance. Thanks anyway!
Of course Raycast would be able to tell you if something is to your left, right, below, above, in front of, or behind you. If you read the script ref I linked you to, you will see in the example that it is checking what is in front of the object by using var fwd = transform.TransformDirection(Vector3.forward)...
You get a Vector that you can compare with the object's transform, via Vector3.Cross and/or Vector3.Dot. I once wrot a script to calculate the angle between two Vectors (including CW or CCW)...
curAngle = Vector3.Angle((curPos - lastPos).normalized, transform.forward);
clockwise = angleDir(transform.forward, (curPos - lastPos).normalized, Vector3.up);
function angleDir(fwd: Vector3, targetDir: Vector3, up: Vector3) {
var perp: Vector3 = Vector3.Cross(fwd, targetDir);
var dir: float = Vector3.Dot(perp, up);
if (dir > 0.0) {
return 1.0;
} else if (dir < 0.0) {
return -1.0;
} else {
return 0.0;
}
}
Answer by Piflik · Jan 01, 2013 at 08:45 PM
Don't think there is an existing script that suits your needs, but you should be able to write one yourself. You could use raycasts or colliders to test if there are obstacles in front of your newly created corridor.