1
votes

I'm making PacMan type game, just for fun and i have a problem. I've created a character and made a map with tilemaps. I added tilemap collider 2d to tilemap and box collider 2d and rigidbody(kinematic) for character. Here is my code for movement:

public class PlayerController : MonoBehaviour
{
    [SerializeField]
    private float _speed = 3.0f;
    private Vector2 _direction = Vector2.zero;


    private void Start()
    {
     
    }

    private void Update()
    {
        Move();

        CheckInput();
    }

    private void CheckInput()
    {
        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            _direction = Vector2.left;
        } else if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            _direction = Vector2.right;
        } else if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            _direction = Vector2.up;
        } else if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            _direction = Vector2.down;
        }
    }

    private void Move()
    {
        transform.localPosition += (Vector3)(_direction * _speed) * Time.deltaTime;
    }
}

I've changed the "Contact pairs mode" but it didn't work. Here is the photo of my problem: collision problem

1

1 Answers

1
votes

Kinematic rigidbodies don’t allow collision. They are meant to be used for walls and things. It would be better to use a dynamic Rigidbody2D, and disable gravity and any other forces you don’t want.

A dynamic Rigidbody is one of the other things you can select instead of kinematic in the drop down menu. It is very important that you set it to dynamic, because dynamic allows there to be forces on the object.

Also, when using a Rigidbody, you don’t want to move it using transform.

I would move it with velocity so it detects collision.

Rigidbody2D rb;
private void Start()
{
    rub = GetComponent<Rigidbody2D>();
}

private void Update()
{
    Move();

    CheckInput();
}

private void CheckInput()
{
    if (Input.GetKeyDown(KeyCode.LeftArrow))
    {
        _direction = Vector2.left;
    } else if (Input.GetKeyDown(KeyCode.RightArrow))
    {
        _direction = Vector2.right;
    } else if (Input.GetKeyDown(KeyCode.UpArrow))
    {
        _direction = Vector2.up;
    } else if (Input.GetKeyDown(KeyCode.DownArrow))
    {
        _direction = Vector2.down;
    }
}

private void Move()
{
    rb.velocity = _direction * _speed * Time.deltaTime;
    //set all of the drag variables on the Rigidbody
    //to very high, so it slows down when they stop moving.
}