Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Question When objects collide they start rotating for a long time, how to turn it off or slow it down?

Discussion in 'Scripting' started by Kujji, Mar 31, 2023.

  1. Kujji

    Kujji

    Joined:
    Oct 20, 2021
    Posts:
    80
    I'm making a multiplayer game in 2D, I don't understand how to fix a very long time of objects rotation after colliding with each other.

    Video of problem:


    Object's components:


    Objects code of moving and rotating:

    Code (CSharp):
    1. using UnityEngine;
    2. using Photon.Pun;
    3.  
    4. [RequireComponent(typeof(Rigidbody2D), typeof(CapsuleCollider2D))]
    5. public class PlayerMover : MonoBehaviour
    6. {
    7.     [SerializeField] private float _speepMoving, _speedRotation;
    8.  
    9.     private Rigidbody2D _rigidbody;
    10.     private Vector2 _direction;
    11.     private PhotonView _view;
    12.  
    13.     [HideInInspector] public FixedJoystick joystick;
    14.  
    15.     private void Start()
    16.     {
    17.         _view = GetComponent<PhotonView>();
    18.         _rigidbody = GetComponent<Rigidbody2D>();
    19.     }
    20.  
    21.     private void FixedUpdate()
    22.     {
    23.         if (_view.IsMine)
    24.         {
    25.             _rigidbody.velocity = new Vector2(joystick.Horizontal * _speepMoving, joystick.Vertical * _speepMoving);
    26.  
    27.             RotatePlayer();
    28.         }
    29.     }
    30.  
    31.     private void RotatePlayer()
    32.     {
    33.         _direction = new Vector2(joystick.Horizontal, joystick.Vertical);
    34.  
    35.         if (_direction != Vector2.zero)
    36.         {
    37.             Quaternion toRotation = Quaternion.LookRotation(Vector3.forward, _direction);
    38.             _rigidbody.MoveRotation(Quaternion.Lerp(transform.rotation, toRotation, _speedRotation * Time.deltaTime));
    39.         }
    40.     }
    41. }
     
  2. Kujji

    Kujji

    Joined:
    Oct 20, 2021
    Posts:
    80
    I increased Angular Drag and this solved problem
     
  3. casezack177

    casezack177

    Joined:
    Aug 10, 2021
    Posts:
    6
    Another option you could use is to Freeze the Z rotation in the Rigidbody2D constraints. This would require you to change rotation directly through code when turning your moving objects. Unity2D is actually a 3D virtual space so the Z axis controls the rotation of 2d sprites. You can look at transform.rotation in order to control the rotation through code.