Search code examples
c#unityscriptunity-game-engine

C# Unity 2D Player Goes through Box Collider


ive got a problem with a player it has RigidBody2D,Box Collider2D ive searched for 2days and no result had used a DontGoThroughThings, and lot of other things, Or maybe did something wrong. i`am making a mobile game and added to script a Input.touches

foreach (Touch touch in Input.touches)
            {
                Vector3 newPosition = transform.position;
                newPosition.y += touch.deltaPosition.y * speed * Time.deltaTime;
                transform.position = newPosition;
            }

And it Got Speed, when i move finger to fast object goes straight out of camera view and he didnt collide with a collider

sorry for bad english Thanks for Your Advice If need more info , i will give details.


Solution

  • Likely the problem is that your object is moving so quickly between frames that it completely misses the collider. You should clamp the maximum speed that your object can go to some reasonable range, rather than using the touch.deltaPosition.y directly. Something like this:

    foreach (Touch touch in Input.touches)
    {
        Vector3 newPosition = transform.position;
        newPosition.y += Mathf.Clamp(touch.deltaPosition.y * speed, MIN_SPEED, MAX_SPEED) * Time.deltaTime;
        transform.position = newPosition;
    }