Search code examples
c#unity-game-enginecollision

Unity - when objects collide they start rotating for a long time, how to turn it off or slow it down?


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:

enter image description here

Objects code of moving and rotating:

using UnityEngine;
using Photon.Pun;

[RequireComponent(typeof(Rigidbody2D), typeof(CapsuleCollider2D))]
public class PlayerMover : MonoBehaviour
{
[SerializeField] private float _speepMoving, _speedRotation;

private Rigidbody2D _rigidbody;
private Vector2 _direction;
private PhotonView _view;

[HideInInspector] public FixedJoystick joystick;

private void Start()
{
    _view = GetComponent<PhotonView>();
    _rigidbody = GetComponent<Rigidbody2D>();
}

private void FixedUpdate()
{
    if (_view.IsMine)
    {
        _rigidbody.velocity = new Vector2(joystick.Horizontal * _speepMoving, joystick.Vertical * _speepMoving);

        RotatePlayer();
    }
}

private void RotatePlayer()
{
    _direction = new Vector2(joystick.Horizontal, joystick.Vertical);

    if (_direction != Vector2.zero)
    {
        Quaternion toRotation = Quaternion.LookRotation(Vector3.forward, _direction);
        _rigidbody.MoveRotation(Quaternion.Lerp(transform.rotation, toRotation, _speedRotation * Time.deltaTime));
    }
}
}

Solution

  • If you don't want rotation of your object, you got to use the freeze rotation property in your rigid body. Right now, the rigid body are hitting themselves and they start spinning without anything to stop their rotation. You you freeze rotation z, it should stop spinning.