W
W
WasTabon2020-10-12 15:58:37
Unity
WasTabon, 2020-10-12 15:58:37

How can you make collisions in 2d so that objects do not enter into each other?

Like there is a wall with a 2d collider and a character with a 2d collider and a 2d rijidbody, but when the character goes into the wall, he enters it, then, as it were, jumps back and so on in a circle, but how can you make sure that he does not fall into the wall, did you just stop?
Here is the script of the movement if anything

void Update()
    {

        if (Input.GetKeyDown(KeyCode.Space))
        {
            rigidbody2D.AddForce(transform.up * jumpForce, ForceMode2D.Impulse);
        }

        if (Input.GetKey(KeyCode.D))
        {
            transform.Translate(Vector2.right * Time.deltaTime * speed);
        }

        if (Input.GetKey(KeyCode.A))
        {
            transform.Translate(Vector2.left * Time.deltaTime * speed);
        }

    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan, 2020-10-12
@WasTabon

The transform.Translate method moves the object, ignoring the physics engine (pushing it into the wall), and then the physics engine tries to do something. In order for the physics to be calculated correctly, you should use the methods in rigidbody2D to push the character, as you do in the case of a space. And you should not use direct translation through transform.Translate and rigid body physics together, otherwise you will get just such problems.

B
Bogdan Erolskiy, 2020-10-12
@B-Erolskiy

Create a Physic Material in the project with Create -> PhysicMaterial, then add this material to the collider in the Material property.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question