Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Rotation animation moves obect's xy

Discussion in '2D' started by unity_1AiyR6KqVk7p1g, Sep 12, 2019.

  1. unity_1AiyR6KqVk7p1g

    unity_1AiyR6KqVk7p1g

    Joined:
    Aug 29, 2019
    Posts:
    2
    Hi people,
    need help, please. I'm trying to animate an object. The animation changes the y position by transform. What happens though is that when I rotate it, it moves its pivot position, thus offsets the whole object.

    Here's the video:


    And the code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class AttackAnimation : MonoBehaviour
    6. {
    7.     public float offset = 0.0f;
    8.     private Animator _attackAnimation= null;
    9.  
    10.     private Vector3 center;
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         _attackAnimation = GetComponent<Animator>();
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update()
    19.     {
    20.         // Use this for initialization
    21.         bool attack = false;
    22.  
    23.         //turn to cursor possition
    24.         center = Camera.main.ScreenToWorldPoint(GetComponent<SpriteRenderer>().sprite.pivot);
    25.  
    26.         Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
    27.         difference.Normalize();
    28.  
    29.         float rotation_z = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
    30.         transform.rotation = Quaternion.Euler(0f, 0f, rotation_z + offset);
    31.  
    32.  
    33.         if (Input.GetMouseButton(0))
    34.         {
    35.             attack = true;
    36.         }
    37.  
    38.         _attackAnimation.SetBool("attack", attack);
    39.  
    40.         GetComponent<SpriteRenderer>().sprite.pivot = center;
    41.     }
    42. }
    43.  
    I should add that the code GetComponent<SpriteRenderer>().sprite.pivot = center; throws an error as the sprite.pivot is read only. No idea how to set it.

    Tx very much!
    V
     
    Last edited: Sep 12, 2019
  2. unity_1AiyR6KqVk7p1g

    unity_1AiyR6KqVk7p1g

    Joined:
    Aug 29, 2019
    Posts:
    2
    OK, I fixed it by moving the rotation script to the parent object. This is it
    .