ScreenPointToRay gives unexpected results?

The results that I’m getting from this script are not what they should be. I’m attempting to get an object to fire from my player to a point in the world which is at the center of the screen, but it always seems to be too low or just off the wall. The further the hit, the more accurate it is, and conversely, the closer, the farther away from the mark it seems to go (though this might be a perspective thing).

p.Launch() is just a function which lerps from the object’s current position to the position given.

With the uncommented version of p.Launch, I get the most accurate results, the situation described above. This shouldn’t really be the case since ray.direction is just a direction vector multiplied by a scalar and shouldn’t give even semi-accurate results unless the player is standing near (0,0,0) in world space.

The commented version is, by far, worse. Technically it works and it’s supposed to give the most accurate results since it’s an actual position vector, but only if you’re aiming at the exact point that it wants, otherwise it shoots them off in all sorts of odd directions, getting more random the less you are facing that point.

void Update () {
	if(Input.GetMouseButtonDown(0)) {
		GameObject newBullet = Instantiate(bullet, transform.position, transform.rotation) as GameObject;
		Projectile p = newBullet.GetComponent(typeof(Projectile)) as Projectile;
		
		Vector3 screenPoint = new Vector3(Screen.width/2.0f, Screen.height/2.0f);
		Ray ray = Camera.main.ScreenPointToRay(screenPoint);
		
		RaycastHit hit;
		Physics.Raycast(ray, out hit);

        // Works but only for a very small section of the world, otherwise, results are very sporadic.
        //p.Launch(hit.point);

        // Moves in the general direction it should, but always too low.
		p.Launch (ray.direction * hit.distance);
	}
}

Vector3 screenPoint = new Vector3(Screen.width/2.0f, Screen.height/2.0f);

You’re missing an axis, not sure if the default will work for you.

EDIT: you’ve got a background object for the raycast to hit, right? You will get strange results should the raycast go on forever (your not limiting it either)

Every time…

Here goes. Turns out, I originally had intended Projectile.Launch() to take a distance vector and add it to the transform of the object, which explains why the uncommented version works better (somewhere between then and when I wrote the above code I forgot about that). The problem with that is that it was spawning at the player, rather than the camera so it was taking the position of the player instead of the camera.

After taking out that bit of code from the Launch function, all I had to do was add the camera’s position to the direction vector:

p.Launch((ray.direction * hit.distance) + Camera.main.transform.position);

And now it works.