Search code examples
c#unity-game-enginecollision-detectionlag

2 circle colliders causing lag in player movement


I am making a game in Unity 2d where if you are in the range of a magnet, you get attracted to it. Attached to the player are 2 circle colliders: one is set as a trigger, which radius can increase or decrease to alter the magnet's range, and the other one isn't set as a trigger to allow it to rest on platforms. I am using this code: transform.Translate(3 * Time.deltaTime, 0, 0); to move the player forward. The player movement is really laggy when it is touching the ground, but it is smoother when it is in the air. The camera movement is silky smooth once the project is exported, so I do not think that it is because I have a slow computer for only the player is laggy. Could someone help me solve this problem? Also it is important to note that when either circle collider is removed, the movement is smooth, so it isn't a problem with the code.


Solution

  • I think that the main issue is that the collision with the ground causes problems with the transform.Translate. I suggest some changes:

    CHANGING THE TRIGGER You should move the collision with the trigger on the magnet, it's way easier for the future if you want to add new magnets and you will see also the application with my changes

    ADDING FORCE Instead of doing a transform.Translate you should add a force so you keep the physics working well and it won't look buggy! You should do:

    FixedUpdate()
    {
       rb.AddForce(Vector2.Distance(transform.position, player.position) * 2);
       
    }
    

    We use FixedUpdate() because it keeps physics working well and rb is the rigidbody of the player and Vector2.distance can be Vector2.right, it depends on what you imagine. If you work with distance force will increase if you go closer.