Aleksa Ristic
Aleksa Ristic

Reputation: 2499

transform.LookAt is going off the gameobject

I am casting some spell and i am setting it direction by LookAt. Problem is that LookAt is setting my spell animation off the gameobject. Object from which i am getting position has scale (3, 3, 3), mesh renderer, sphere collider, and rigidbody. (other colliders are on child objects). Here is the code i am using for casting spell:

public void castSpell(GameObject caster, Transform otherTransform, float duration)
{
    if(animationEnabled)
    {
        foreach(var a in animator)
        {
            foreach(var b in a.bools)
            {
                a.animator.SetBool(b.parameterName, b.parameterValue);
            }
            foreach(var i in a.ints)
            {
                a.animator.SetInteger(i.parameterName, i.parameterValue);
            }
            foreach(var f in a.floats)
            {
                a.animator.SetFloat(f.parameterName, f.parameterValue);
            }
        }
    }

    GameObject Temporary_Spell_Handler;
    Temporary_Spell_Handler = Instantiate(_Spell, Spell_Emitter.transform.position, Spell_Emitter.transform.rotation) as GameObject;

    ParticleSystemRenderer pr = Temporary_Spell_Handler.GetComponent<ParticleSystemRenderer>();
    float dist = Vector3.Distance(caster.transform.position, otherTransform.position);

    //Add Spell Script to the casted spell so it handes damage and everything about spells.
    Spell tempSpell = Temporary_Spell_Handler.GetComponent<Spell>();
    tempSpell.caster = caster;

    if(b_lenghtScale)
    {
        pr.lengthScale = -lenghtScale;
    }

    if(lookAtEnemy)
    {
        Temporary_Spell_Handler.transform.LookAt(otherTransform);
    }

    Destroy(Temporary_Spell_Handler, duration);
}

and here is the image how it looks like:

enter image description here

I found the problem. My ball is scaled to (3, 3, 3), so it went up and pivot of the object stayed down. So how can I overcome this problem?enter image description here

Upvotes: 0

Views: 104

Answers (1)

Aleksa Ristic
Aleksa Ristic

Reputation: 2499

I created empty gameobject and make it a parent to my ball. Then i set gameobjects position (it is pivot now) to where i wont (around center of ball y=5) and then on the ball i did the opposite (y= -5).

Then to the gameobject i created as pivot i added tag pivotChange and then in my castSpell script i made this change at lookAtEnemy part:

    if(lookAtEnemy)
    {
        if(other.transform.parent != null && other.transform.parent.gameObject.tag == "pivotChange")
        {
            Temporary_Spell_Handler.transform.LookAt(other.transform.parent.gameObject.transform);
        }
        else
        {
            Temporary_Spell_Handler.transform.LookAt(other.transform);
        }
    }

And it is working okay.

Upvotes: 1

Related Questions