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. Dismiss Notice

What is the advantage of using Rigidbody2D.Cast in order to detect collisions?

Discussion in 'Scripting' started by egonspengler_84, Jun 18, 2021.

  1. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    So I've been following an official Unity tutorial over the last couple of days where the tutor uses Rigidbody2D.Cast in order for a game object that has a Kinematic Rigidbody2D to detect collisions. Here is the specific video in which he starts to use the Cast function:


    I've been trying to follow what he is doing but I was really overwhelmed by all the stuff you need to do in order to get the Cast to work etc. I'm just wondering what is the actual advantage of using this function as opposed to just shooting a bunch of raycasts from each side of the game object and detecting collisions this way? Is it more reliable or something?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    I suppose you would be able to accurately simulate the motion of the body through the scene, including whatever complicated collider setup it may have (multiple colliders, polygon colliders, etc).
     
  3. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    If I have a game object that just has a BoxCollider2D and Kinematic Rigidbody2D attached to it and I'm trying to simulate gravity by using the Rigidbody2D.MovePosition function to move the object downwards and have it collide with the ground underneath then is there any point in using Rigidbody2D.Cast in this case?

    Would I be better off just firing a couple of raycasts from the bottom of the object and make the object stop once the raycast's distance is equal to zero? Or something along those lines?
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    You'd probably be better off using Physics2D.BoxCast if the only shape involved is a BoxCollider2D
     
  5. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    Okay I understand.

    Out of curiosity.....what is the most common way of simulating gravity and ground collision with a game object that has a a Kinematic Rigidbody2D and a BoxCollider2D?

    I assume that a lot of 2D platformer games would consist of a Player game object with a Kinematic Rigidbody2D and they would simulate gravity by using something like the MovePosition function but how do people usually make the game object stop flush against the ground?
     
    Last edited: Jun 18, 2021
  6. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,529
    I replied here.