0
\$\begingroup\$

I have a object that pushing rigidbody forward when it's instantiated:

GameObject grenade = Instantiate(projectilePrefab, shootPoint.position, shootPoint.rotation);
grenade.GetComponent<Rigidbody>().velocity = transform.forward.normalized * 50;

It seems fine, but when I ran the game, projectile always not going straight and it's little bit moving left or right.

So I thought that shoot point wasn't pointing the right direction or my crosshair didn't centered properly, but unfortunately there were nothing wrong with them.

enter image description here

enter image description here

enter image description here

I think there's no extra forces that affects physics in my scene except gravity, and gravity has default settings which only affects downside. But why projectile doesn't go straight and move little bit left?

What am I missing?

\$\endgroup\$
1
\$\begingroup\$

As previously answered. If you spawn your projectile offset from the camera, and shoot it in the direction of a transform attached to the rifle then it won't line up with the camera because the rifle is not lined up with the camera

The way to solve this is to do one of the following:

A) Shoot the projectile from the camera.

B) Project the crosshair out from the rifle instead of the camera.

C) Force the rifle to line up with what the camera is looking at.

You'll find that most FPS games go with option A. Recently there have been a few games that do a combination of options B and C.

\$\endgroup\$
2
\$\begingroup\$

Those calculations you made are taking into account a direction that is forward of the camera center. But you are instanciating the grenade in an arbitrary transform called ShootPoint.

so how to actually aim with the camera and shoot toward that direction ? i guess that's your question.

GameObject grenade = Instantiate(projectilePrefab, shootPoint.position, shootPoint.rotation);
grenade.GetComponent<Rigidbody>().velocity = Camera.main.transform.forward.normalized * 50;

Not the cleanest and modular code out there as your grenade have a direct dependency on Camera.main but it should solve your aiming issues.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.