- Home /
how to aim an object at another object
I'm using a ParticleSystem to make a gun shoot a bullet at a target object.
I need to instantiate the ParticleSystem prefab at the position of the gun and pointed at the target object so that the bullet particle flies along the path from one to the other.
I have the position of the source (the gun) and the destination (the target) as Vector3s, and to call Instantiate I need a position Vector3 and a rotation Quaternion.
I've googled and searched Unity answers this quite a bit, and as I understand it I should be getting the direction from the source to the destination positions and then use Quaternion.LookRotation to turn that into a rotation:
Vector3 source = GetSourcePosition();
Vector3 dest = GetDestPosition();
Quaternion rotation = Quaternion.LookRotation((dest - source).normalized);
Instantiate(bulletEmitterPrefab, source, rotation);
Unfortunately no matter what I do I can't get it to work - the ParticleSystem always just shoots straight up.
It would be easier to make the particle system LookAt(theTarget) before emitting. Or keep the particle system as a child of the muzzle of the gun so it's always facing the right direction.
Answer by ghosttie · Mar 13, 2015 at 12:36 AM
It turns out my code was right except that I'd rotated the prefab in the editor and this rotation is lost when you instantiate it, so I had to add that rotation to the one I'd calculated:
rotation *= Quaternion.Euler(90, 0, 0);
Ok good, however, as an extra note, you should fix your prefab and set its forward orientation to be the +ve z-axis. This is the standard.
ie. forward = +ve Z-axis
Once you set that, you will not need to worry about adding rotation etc.