- Home /
Changing the forward rotation for LookAt
Hi all,
I have the following red projectiles heading towards a spacecraft that rotates around a planet: I'm having difficulty rotating the projectile so either thin end faces towards the spaceship. In LookAt
I've tried giving it various axis to define the up rotation, I've also tried rotating the prefab a bunch, however, they always face the ship like that. Any help is appreciated =)
Answer by Hellium · Apr 18, 2018 at 01:47 PM
Your prefab is not correctly oriented. Here, your capsule is along the Y-axis (green), but it should be on the Z-axis (blue).
Since we don't know how your prefab is built, it will be ahrd to advise you anything to fix the prefab (best solution). Maybe, you could make the capsule a child of an empty gameObject which will be your new prefab. Then, rotate the capsule so that its main axis is oriented on the Z-axis of the empty.
Otherwise, you will have to play with rotation angles in your code:
bullet.transform.rotation = Quaternion.Euler( 90, 0, 0 ) * Quaternion.LookAt( target.transform.position - bullet.transform.position ) ;
// OR
//bullet.transform.rotation = Quaternion.LookAt( target.transform.position - bullet.transform.position ) * Quaternion.Euler( 90, 0, 0 ) ;
Answer by Krishx007 · Jul 15, 2020 at 05:19 PM
//This code uses lookDirection instead of lookPostion but you can easly calc direction from position
// direction = lookAtPos-lookerPos
//Makes the gameObject look towards "lookDirection" with customizable "lookerForwardVector"
public static Quaternion LookAtDirection(GameObject looker, Vector3 lookAtDirection, Vector3 lookerForwardVector)
{
Transform inputTransform = looker.transform;
inputTransform.rotation = Quaternion.LookRotation(lookAtDirection); //calculating look rotation
//Changes the LookAt alignment, like you can use "Vector3.up" vector instead of default "Vector3.forward"
inputTransform.Rotate(GetForwardVectorAngleOffest(lookerForwardVector), Space.Self);
return inputTransform.rotation;
}
static Vector3 GetForwardVectorAngleOffest(Vector3 forwardVector)
{
if(forwardVector == Vector3.up)
return new Vector3(90, 0, 0);
if (forwardVector == Vector3.right)
return new Vector3(0, -90, 0);
return new Vector3(0, 0, 0); ;
}