- Home /
Rotate to Center of Screen
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?
Well I don't want the bullet to look at an object itself. I don't want a child object for the camera either. $$anonymous$$y camera can be a little rickety because of my custom scripts. I want it to face the center of the screen.I thought I could maybe solve this with ScreentoWorld or something.
Well it's 3d person and the bullet spawns at the character, it would look rather weird if the bullet spawns exactly in front of the camera ins$$anonymous$$d. How can I solve this in a different way?
I have an idea how I could fix this but I'd rather try a different approach. I thought maybe an object that's exactly in the middle of the camera but always clamps to the object that's exactly in front of it, no matter how far the distance. Then I'd have the bullet face this target object so it will go there. Is this a solid approach?
Answer by aldonaletto · Apr 15, 2012 at 09:38 PM
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)));
...
Answer by rutter · Apr 15, 2012 at 01:45 AM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613070333im_/https://answers.unity.com/themes/thub/images/avi.jpg)