- Home /
How to find an object directly above another w/out Raycast?
I am trying to make an object that applies a little air blast to anything that gets above it. I am a little stuck here. The air blaster (aka Jet) should be able to find out if something is directly above it (relative to the jet's orientation) and, if so, apply a wind force that blasts the other object away. I have everything working except I can't make it work only if the other object is DIRECTLY above it.
I've tired using the dot product between the up Vector and the Vector between the object and the jet; I've tried a distance check; I've tried a combination of the two; I've even tried a Raycast. The Raycast would've worked only it would hit other objects (ones that I DON'T want to blast) and return Null Reference Exceptions.
Here's my code as it looks now:
public class JetController : MonoBehaviour
{
public int windForce = 0;
public GameObject[] balls;
// Use this for initialization
void Start ()
{
balls = GameObject.FindGameObjectsWithTag ("Ball");
}
// Update is called once per frame
void FixedUpdate ()
{
Vector3 wind;
balls = GameObject.FindGameObjectsWithTag ("Ball");
for (int i = 0; i < balls.Length; i++)
{
Vector3 heading = balls[i].transform.position - transform.position;
if (balls[i].transform.tag == "Ball")
{
if (Vector3.Distance(balls[i].transform.position, transform.position) < 2)
{
if (Vector3.Dot(heading, -transform.forward) > 0)
{
print (Vector3.Dot(heading, transform.up));
wind = transform.up * windForce;
balls[i].rigidbody.AddForce(wind);
}
}
}
}
}
If anyone could help, that would be much appreciated!
Answer by supernat · May 29, 2014 at 03:44 AM
There are a couple of ways to handle it. First off, if you wanted to use ray casts, you can limit the ray cast to specific layers. So if you assigned the balls to a Ball layer, pass the ball layer to the raycast method, and it will only return collisions with balls. If you want to use the dot product, I'm a bit confused by you using the trasform.forward for the angle test (negative of that no less) and transform.up for the force. I suspect your Dot(heading, -transform.forward) is returning 0 when the object is directly above the jet. You probably mean Dot(heading, transform.up) here. Then testing > 0 will result in anywhere from the object being parallel with the jet UP direction all the way to being ALMOST 90 degrees perpendicular to the jet UP direction. Hope that makes sense, but feel free to comment if I'm misinterpreting the code.
Also, you don't need to check if transform.tag == "Ball" on line 21 since you already know this.
Your answer
Follow this Question
Related Questions
AddForce to the Left? 3 Answers
Unity Rotate Raycast on Quaternion 1 Answer
How to access component that the raycast hit 1 Answer
My Raycast on awake fires and will not change Help! 0 Answers
Multiple Raycasts & Vector3.Reflects in a row. How? 1 Answer