Unity Prefab spawn incorrect rotation

2.2k views Asked by At

I have the following simple prefab:

enter image description here

When I add this to my scene, it looks like this:

enter image description here

Very neat!

Then I have the following script on my Character:

public class MageController : MonoBehaviour {
    public GameObject Spell;
    public float SpellSpeed;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown(KeyCode.H)) {
            GameObject newSpell = Instantiate(Spell);
            newSpell.transform.position = transform.position;
            newSpell.transform.rotation = Quaternion.LookRotation(transform.forward, transform.up);
            Rigidbody rb = newSpell.GetComponent<Rigidbody>();
            rb.AddForce(newSpell.transform.forward * SpellSpeed);
        }
    }
}

The goal is of course to make sure that the fireball is spawned correctly (with the tail behind it)

This works when I stand at 0.0.0; it looks like this:

enter image description here

However, if I turn around it looks like this:

enter image description here

As you can see, the rotation of the fireball is not correct (in the above incorrect image it is flying away from me, however, the tail is in front).

What am I doing wrong? How can I make sure that the tail is always correctly placed?

Update after following the guidance of PlantProgrammer it still turns incorrectly :(

Look at the image below!

enter image description here

1

There are 1 answers

3
PlantProgrammer On BEST ANSWER

You want to use the forward direction of the player and not it's rotation, when instantiating the fireball. (Remember: transform in your script is the player transform not the fireball transform.) Check https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html. LookRotation will return the rotation based on player's forward and up vectors.

GameObject newSpell = Instantiate(Spell);
newSpell.transform.position = transform.position;
newSpell.transform.rotation = Quaternion.LookRotation(transform.forward, transform.up);

Not part of your question, but I would also suggest letting the fireball fly in the forward direction of itself not the player (as this leaves more room for later modifications)

rb.AddForce(newSpell.transform.forward * SpellSpeed);