I’m trying to create an aim mode, with an over-the-shoulder camera.
Right now when aiming, I raycast from the shoulder camera towards the center of the screen.
My gun, and bullet spawn point are on a different transform.
Once I Instantiate a bullet, I call the LookAt(raycasthit.point) on the RigidBody of the instantiated object and add force to shoot.
Problem is, that the path that my bullet travels is obviously different from the ray from the shoulder camera, resulting in inaccurate shots.
How do i get a proper trajectory independent of where the bullet spawn point is?
My code:
void ShootMethod()
{
Ray ray = ShoulderCam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;
Vector3 AimpPoint;
if (Physics.Raycast(ray, out hit))
{
if (hit.point != null)
{
AimpPoint = hit.point;
}
else
{
//2000 maybe not enough
AimpPoint = ray.GetPoint(2000);
}
}
var bulletclone = Instantiate(bulletPrefab, barrelLocation.position, Quaternion.identity);
var tempFlash = Instantiate(muzzleFlashPrefab, barrelLocation.position, barrelLocation.rotation);
bulletclone.gameObject.transform.LookAt(hit.point);
bulletclone.GetComponent<Rigidbody>().AddRelativeForce(bulletclone.transform.forward * shotPower);
Destroy(bulletclone, 10f);
Destroy(tempFlash, 0.5f);
CasingRelease();
}
Hopefully my question is clear.