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.

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);

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.