Home > Back-end >  Why is the object changes length while rotating?
Why is the object changes length while rotating?

Time:12-27

I'm trying to make an object (weapon) rotating toward the mouse position.But i have encountered a problem that this object somehow, rotates not only in z-axis, so with rotation it becames longer and smaller.

Here is the picture of problem

With rotation the lenght of weapon is increasing

Here's the code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class Rotation : MonoBehaviour
{
    private Vector3 mouseP;       
    void Update()
    {
        mouseP = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector3 direct = transform.position - mouseP;
        direct.Normalize();
        float Angle = Mathf.Atan2(direct.y, direct.x) * Mathf.Rad2Deg;
        Quaternion rotate = Quaternion.Euler(0, 0, Angle);
        transform.rotation = rotate;
    }
}

I don't understand why this happening because at this line: Quaternion rotate = Quaternion.Euler(0, 0, Angle); I directle wrote that rotation should happen only on z-axis. Any ideas how can i solve this problem?

CodePudding user response:

Probably because its parent object is also scaled? -> the two scales add up .. it looks like it is nested under the green block which is bigger in Y direction => also the child is bigger in Y direction

Any ideas how can i solve this problem?

Well, the most trivial would be to not scale the parent objects.

In general I personally would strictly separate the object roots itself (all unscaled) and only scale the leaf children containing the visuals.

In your case I would e.g. use a hierarchy like

- PlayerRoot (unscaled)
  |-- PlayerBody (scaled green block)
  |-- Point (unscaled)
      |-- GunSprite (scaled grey block with local translation)

This way it is ensured there is no scaling in the entire hierarchy of the gun and you can rotate the Point object without facing any scaling issues

  • Related