Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question Collision While Using Transform.Translate

Discussion in '2D' started by unity_3ddragon, May 18, 2024.

  1. unity_3ddragon


    May 13, 2024
    I'm working on creating a platformer game where when the player presses a button they teleport 3 units in a direction depending on which button they press but I've found that the player can just teleport straight through colliders. Is there a way to fix this.
  2. samana1407


    Aug 23, 2015
    Here’s what you need to know about how your player is set up. Ideally, the player should have a Rigidbody2D with a Collider2D attached. If your object has a rigid body, this means you must manipulate its position in space ONLY through the methods provided by the physics system attached to it. In other words, all physical actions should be managed only through physics methods. Therefore, Transform.Translate is not suitable; instead, use something like:

    Code (CSharp):
    1. private Rigidbody2D _rb2d;
    3. void Start()
    4. {
    5.     _rb2d = GetComponent<Rigidbody2D>();
    6. }
    8. void Update()
    9. {
    10.     if (Input.GetKeyDown(KeyCode.RightArrow))
    11.     {
    12.         _rb2d.MovePosition(_rb2d.position + Vector2.right * 3);
    13.     }
    15.     if (Input.GetKeyDown(KeyCode.LeftArrow))
    16.     {
    17.         _rb2d.MovePosition(_rb2d.position + Vector2.left * 3);
    18.     }
    19. }
    Additionally, don't forget to set the Collision Detection property of the Rigidbody2D to Continuous in the inspector. This ensures that the object, when moving at high speeds (like your large step of three cells), calculates collisions correctly and doesn’t teleport through colliders.
    spiney199 likes this.