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