Collision While Using Transform.Translate

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.

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:

private Rigidbody2D _rb2d;

void Start()
{
    _rb2d = GetComponent<Rigidbody2D>();
}

void Update()
{
    if (Input.GetKeyDown(KeyCode.RightArrow))
    {
        _rb2d.MovePosition(_rb2d.position + Vector2.right * 3);
    }

    if (Input.GetKeyDown(KeyCode.LeftArrow))
    {
        _rb2d.MovePosition(_rb2d.position + Vector2.left * 3);
    }
}

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.

1 Like