Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question (new dev) 2d rigidbody2d not working with collision [solved]

Discussion in '2D' started by omer9005, Aug 15, 2022.

  1. omer9005

    omer9005

    Joined:
    Aug 15, 2022
    Posts:
    2
    hi so i tried to use rigidbody2d and a box collider and a collision layer to block my player from moving into certain objects in the environment but i cant seem to make it work i would really appreciate the help as I'm really new to unity and don't really know what to do,
    my code:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.InputSystem;

    public class playerController : MonoBehaviour
    {
    // Start is called before the first frame update
    public float moveSpeed=1f;
    public float collisionOffsett=0.05f;
    public ContactFilter2D movementFilter;
    Vector2 movmentInput;
    Rigidbody2D rb;
    List<RaycastHit2D> castCollisions = new List<RaycastHit2D>();
    void Start()
    {
    rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {

    }
    private void FixedUpdate(){
    if(movmentInput!=Vector2.zero){
    int count= rb.Cast(
    movmentInput,
    movementFilter,
    castCollisions,
    moveSpeed*Time.fixedDeltaTime+collisionOffsett
    );
    if(count==0){
    rb.MovePosition(rb.position+movmentInput*moveSpeed*Time.fixedDeltaTime);
    }
    }
    }
    void OnMove(InputValue movmentValue){
    movmentInput= movmentValue.Get<Vector2>();
    }
    }
    screengrab of my scene with the collider
    upload_2022-8-15_21-58-54.png
    please help it is really appreciated
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,964
    I don't see any green collider on the player. Is that just because he's not selected?

    Why not press play, pause, then drop a sprite into the scene with a collider and rigidbody2d and see if it bounces on your level chunks?
     
  3. omer9005

    omer9005

    Joined:
    Aug 15, 2022
    Posts:
    2
    it was because he wasn't selected also after using your trick i realized "is trigger" wasn't active, at least i solved it now, ty
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,623
    FYI: When posting code, please always use code-tags. Plain text is awful for code.

    Thanks.