Just a quick little question I think. I’m instantiating bullets that apply force to themselves and it works perfectly. But I want them to when instantiated, face the center of the screen.
So basically when they fire they will initially go to the center of the screen. (Unless you move.)
I thought this might be solved by rotating the bullet when it’s spawned or even in the instantiate settings, so it will face the center of the screen. Anyone any suggestions on how to do this?
The screen is a 2D space, thus its center in the 3D world is actually a line starting at the camera position and going in the camera forward direction.
If you can instantiate the bullet at the camera position, things are easier:
var camTransf = Camera.main.transform;
var bullet = Instantiate(bulletPrefab, camTransf.position, camTransf.rotation);
...
But if the bullet is instantiated at any other point outside the “screen center line”, its trajectory can at most cross the center line at some point. If you want this point to be at 100 units from the camera, for instance, you could use this:
// create the bullet with zero rotation...
var bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity);
// then rotate it to the screen center at 100 units:
bullet.transform.LookAt(Camera.main.ViewportToWorldPoint(Vector3(0.5, 0.5, 100)));
...
If you know where you want the bullet to face, you can call LookAt() on its transform component. You can make that call every time you want the bullet to change directions (once right after its spawned, once every frame, or some mix).
You can see some simple examples at the page I’ve linked, or at this page from the Unity manual, which covers spawning and facing projectiles.