How to use RigidBody2D.Cast

Iurii 3 years ago updated 3 years ago 2

i am a complete noob in C# and Bolt is an amazing tool that lets me do simple scripting.

My question is about RigidBody2D.Cast, I want to use it to check if my player will hit the wall on the next turn, since my game is turn-based i want to prevent the player from moving any further, closer to the wall, knowing that he will collide with it. I have background tiles with composite collider, as well as a collider on the player.

I am 100% sure that my player is hitting the wall at the point when screenshot is done, but RigidBody2D.Cast keeps returning me zero.
(I double check that collision is happening with regular ray.Cast, but i want to use collider shape instead for better precision)

My idea on how it should work is based on this example, which i found on Unity Forum:

    Rigidbody2D rb = GetComponent<rigidbody2d>();
    RaycastHit2D[] hitResults = new RaycastHit2D[5];
    int numberHit = rb.Cast(Vector3.right, hitResults, 5);
    if(numberHit > 0)
       print("Hit " + numberHit + " colliders.");
       for (int i = 0; i < numberHit; ++i) print("Hit this: " + hitResults[i].collider.name);

    So in my flow macro I want to check too if number of collisions is grater than o and prevent player from moving further.

    Not sure what am I doing wrong and if it is the best way to do it, will appreciate any advise.
    Thank you, here is the screenshot:

    Bolt Version:
    Unity Version:
    Scripting Backend:
    .NET Version (API Compatibility Level):

    Hi Lurii, answered your question on the Unity forum!

    Pasting here:

    You're well on your way already!
    Instead of just logging the result of Cast, use the Branch unit to check an "if" condition, and use a Greater Than unit as the condition. In the Greater Than unit, plug the result of Cast as the first input, and leave 0 for the second.

    Hello Lazlo, thanks for the reply,
    yes i do understand what to do with the result,
    but my problem was that RigidBody2D.Cast always returns me 0,
    i thought that it should return number of collisions,
    and i thought that i was doing something wrong with the list...
    And I was pretty sure that collisions are there cause i double check them with ray.Cast

    will try to mess with the parameters... maybe i made a mistake somewhere else, thanks!