Search Unity

Character tries to cross the box collider 2D

Discussion in 'Physics' started by LTLeonardo, Dec 30, 2015.

  1. LTLeonardo

    LTLeonardo

    Joined:
    Nov 13, 2015
    Posts:
    20
    Hello,
    When the character touch on a wall that has Box Collider he does not pass. Correct.

    The problem is that if I keep moving the character against the wall he is trying to cross the wall, back and forth, back and forth, back and forth ...

    The character is tremendous, as I fix this?

    Follows my movement script.

    Code (CSharp):
    1. player.transform.Translate(-Vector2.right * 2f * Time.deltaTime);
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    Don't use transform.translate for movement if you are using physics as well. Try to use Rigidbody2D.MovePosition instead.
     
  3. LTLeonardo

    LTLeonardo

    Joined:
    Nov 13, 2015
    Posts:
    20
    Thank you PGJ worked :)

    I used this code to move the character


    Code (CSharp):
    1. public class Player : MonoBehaviour
    2. {
    3.     public Rigidbody2D player;
    4.     private Vector2 speedPlayerX;
    5.     private Vector2 speedPlayerY;
    6.  
    7.  
    8.     void Start ()
    9.     {
    10.         player = GetComponent<Rigidbody2D>();
    11.         speedPlayerX = new Vector2(2, 0); // move at position X
    12.         speedPlayerY = new Vector2(0, 2); // move at position Y
    13.     }
    14.  
    15.     void Update()
    16.     {
    17.         //Mount the condition before inserting this code
    18.         player.MovePosition(player.position + speedPlayerX * Time.deltaTime); // Move Right
    19.         player.MovePosition(player.position + -speedPlayerX * Time.deltaTime); // Move Left
    20.  
    21.         player.MovePosition(player.position + speedPlayerY * Time.deltaTime); // Move Up
    22.         player.MovePosition(player.position + -speedPlayerY * Time.deltaTime); // Move Down
    23.     }
    24. }
    Beautiful Code ;)