简体   繁体   中英

Unity2D character glitches through box collider instead of stopping

I'm making a small game in Unity and I'm not very experienced in it yet. I am trying to fix a bug in movement, where instead of stopping when it runs into a 2D box collider, it still makes the character through the box collider, and it just gets forced into the wall. I've tried looking this up on google and StackOverflow, but I can't find the same problem I'm facing. Any help would be appreciated!

Movement script:

public class PlayerMove : MonoBehaviour
{
    public float moveSpeed = 5f;

    public SpriteRenderer playerSpriteRenderer;

    public Animator animator;

    public bool isGrounded = false;

    public static Rigidbody2D rigidbody2D;
    void Awake()
    {
        rigidbody2D = gameObject.GetComponent<Rigidbody2D>();
    }
    
    void Update()
    {
        
        Jump();
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
        transform.position += movement * Time.deltaTime * moveSpeed;
    }
}
        

If you want to make it collide try using rigidbody.velocity . transform.position is for non-collider objects.

So, your code should be:

rigidbody2D.velocity = movement * moveSpeed;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM