- Home /
Question by
siryami · Mar 10, 2014 at 04:19 PM ·
collisionraycastcolliderraycasting
raycast not colliding
I am simply trying to cast a ray between to spheres, but it seems as though the ray isn't colliding.I've read it helps to move it to FixedUpdate, but that isn't working either. I've drawn the ray, and they are obviously touching, so what exactly am I missing?
public class raytest : MonoBehaviour {
GameObject SP,SP2;
// Use this for initialization
void Start () {
SP = GameObject.CreatePrimitive(PrimitiveType.Sphere);
SP2 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
SP.transform.position = new Vector3(-3,2,-2);
SP2.transform.position = new Vector3(-3,2,2);
}
// Update is called once per frame
void Update () {
}
void FixedUpdate () {
RaycastHit hit;
if(Physics.Raycast(SP.transform.position, SP2.transform.position, out hit)){
Debug.Log(hit.collider.name);
Debug.Log(SP.transform.position);
}
Debug.DrawLine(SP.transform.position, SP2.transform.position,
Color.red,7,true);
}
}
Comment
Best Answer
Answer by robertbu · Mar 10, 2014 at 04:22 PM
Update() is fine. This code does not belong in FixedUpdate(). Raycast() takes a position and a direction, not two positions. There is a Physics.LineCast() which takes two positions. But if you want Raycast(), change your line to:
if(Physics.Raycast(SP.transform.position, SP2.transform.position - SP.transform.position, out hit)){
By subtracting 'SP.transform.position' we create a direction vector from the SP.transform.position to SP2.transform.position.