help with onCollisionEnter2D

I’m working on a top down mobile game, and would like to cancel my player’s movement whenever they collide with an object. As far as I can tell, everyone says that adding onCollisionEnter2D to my script should do that, but when I try the following script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed;
    public Rigidbody2D rb;
    public Vector2 pos;

    // Update is called once per frame
    void Update()
    {
        BoxCollider2D playerCollider = GetComponent<BoxCollider2D>();
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            RaycastHit2D hitInfo = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(touch.position), Camera.main.transform.forward);
            pos = Camera.main.ScreenToWorldPoint(touch.position);
        }

        if ((Vector2)transform.position != pos)
        {
            transform.position = Vector3.MoveTowards(transform.position, pos, moveSpeed * Time.deltaTime);
        }
    }

    void onCollisionEnter2D(Collision2D col)
    {
        Debug.Log("Collided with " + col.collider.name);
    }
}

Nothing appears in the console whenever I’m running my character into a building. So am I doing something wrong? I can’t figure out what’s wrong. My guess is something to do with the fact that its my player’s boxcollider hitting the object and not the rigidbody, but I’m unsure. Thanks for any direction or assistance.

No, everyone is telling you to add OnCollisionEnter2D. C# is case sensitive.

Maybe they should also tell you that if you want to move a 2D Collider then it should be attached to a Rigidbody2D and you move that via its API. The Rigidbody2D will then update the Transform. By manipulating the Transform directly, you’re just bypassing it and stomping over what it’s trying to do.

1 Like