Home > Software design >  Unity. Instantiate object in Local Space
Unity. Instantiate object in Local Space

Time:09-22

This should be simple!

I'm trying to instantiate a particle effect on my character, and i need it to be 1 on the Z axis of the characters local space. i.e. so its always 1 in front of the character.

This is my current code:

public void PlayEffect()
        {
            Instantiate(slashEffect, wielder.transform.position   new Vector3 (0, 1, 1), wielder.transform.rotation) ;
        }

Currently this is causing it to spawn always z 1 in world space, meaning sometimes its infront of my character and sometimes its behind me, depending on which way i'm facing.

What is the correct way to do this? :)

CodePudding user response:

You can use Transform.TransformPoint

Transforms position from local space to world space.

like e.g.

public void PlayEffect()
{
    Instantiate(slashEffect, wielder.transform.TransformPoint(new Vector3 (0, 1, 1)), wielder.transform.rotation) ;
}

This takes the 0, 1, 1 as a vector in the local space of your wielder meaning, if you would create a child object and set this to be its local position, this is where your object will be spawned in world space.

Note that this takes also the scaling of the wielder into account!

If you do not want to take the scaling into account rather use the Quaternion operator * like

public void PlayEffect()
{
    Instantiate(slashEffect, wielder.transform.position   wielder.transform.rotation * new Vector3(0, 1, 1), wielder.transform.rotation) ;
}

What this does is using the world space offset vector 0, 1, 1 but then rotates that vector without chaning its magnitude according to the wielder rotation in the world space.

CodePudding user response:

Our you can try:

public void PlayEffect()
        {
            Instantiate(slashEffect, wielder.transform.localPosition   new Vector3 (0, 1, 1), wielder.transform.rotation) ;
        }

as transform.localPosition takes local position of that gameobject.

  • Related