- Home /
C# Raycast goes straight into the air
I've done a raycast before which worked perfectly and went straight as it was supposed to but as i was making a different script containing raycast which is almost exactly the same, it just goes straight into the air. this is the update part of the script:
if (Input.GetKeyDown(KeyCode.F) && curAmmo > 0)
{
Vector3 spreadEffect = new Vector3(Random.Range(-spread,spread),Random.Range(-spread,spread),Random.Range(-spread,spread));
curAmmo--;
muzzleLight.enabled = true;
GameObject traceSpawn = Instantiate(tracer, muzzleLight.transform.position, muzzleLight.transform.rotation) as GameObject;
muzzleDelay = Time.time + 0.1f;
StartCoroutine(armanim.Recoil(recoil));
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f,0.5f,0));
RaycastHit hit;
print ("took a shot");
if (Physics.Raycast(ray, out hit, range))
{
Debug.DrawRay(ray.origin, hit.point, Color.blue, 1);
if (hit.collider.gameObject != gameObject)
{
hit.point = hit.point + hit.distance * spreadEffect;
StartCoroutine(traceSpawn.GetComponent<TrailMove>().MoveTo(hit.point));
print ("got here");
if (hit.collider.gameObject.tag == "Cube")
{
print ("hit cube");
hit.collider.rigidbody.AddForce(-transform.forward * damage);
}
}
}
}
if (Time.time > muzzleDelay)
{
muzzleLight.enabled = false;
}
also, when i draw a ray with Debug.DrawRay and do Camera.main.transform.position then Camera.main.transform.forward it prints a ray going forward then when i do new Ray instead of Camera.main.ViewportPointToRay it doesn't work.
Answer by robertbu · Feb 21, 2014 at 04:39 PM
Your problem is in your Debug.DrawRay() function, not in your Physics.Raycast(). Debug.DrawRay() takes a position and a direction. You are passing it two positions. You can do one of:
Debug.DrawLine(ray.origin, hit.point, Color.blue, 1);
Or:
Debug.DrawRay(ray.origin, (hit.point-ray.origin).normalized * someDistance, Color.blue, 1);
Or:
Debug.DrawRay(ray.origin, ray.direction * someDistance, Color.blue, 1);
Answer by whydoidoit · Feb 21, 2014 at 04:39 PM
You are using DrawRay with two points - that's DrawLine - either:
Debug.DrawRay(ray.origin, hit.point - ray.origin, Color.blue, 1);
Or use DrawLine with the two points.
Your answer
Follow this Question
Related Questions
How do I move a raycast back on objects z axis? 1 Answer
How To Move Object To Terrain Slope in C# With Raycast? 2 Answers
[C#] UNET Client raycast not the same as Server raycast 2 Answers
[C# / Unity] Raycast Ignoring Self / Offsetting Instantiations? 0 Answers
Place Gameobject within a specific tranform value 3d 3 Answers