box2d-netstandard icon indicating copy to clipboard operation
box2d-netstandard copied to clipboard

How to use Raycast?

Open Pastor111 opened this issue 2 years ago • 4 comments

Hi, i was wondering if somebody has an example on how to use Raycast. The implementation showed in the docs does not quite work for me

Pastor111 avatar Sep 19 '21 08:09 Pastor111

Hi @Pastor111, thanks for opening this issue. In my free time (to be honest, I have very little time right now) I'm working on a game project maple-fighters and plan to add the ability to attack mobs and use Raycast for this (JFYI, I'm using Box2D v1.0 there).

When it'll be ready - i'll add a comment here with an example 😄

codingben avatar Sep 20 '21 21:09 codingben

Ok, thanks for you time(and also nice project)

Pastor111 avatar Sep 21 '21 07:09 Pastor111

@Pastor111, I have a piece of code for it:

        /// <summary>
        /// Ray-trace and get closest hit
        /// </summary>
        /// <param name="pos">Ray emitting position</param>
        /// <param name="angle">Ray emitting angle</param>
        /// <param name="maxDist">Maximum measurement distance</param>
        /// <param name="hit">Closest hit distance (if hit)</param>
        /// <returns>trye if hit, false if not</returns>
        public bool RayTrace(Vector2 pos, float angle, float maxDist, out float hit)
        {
            Vector2 endPos = pos + new Vector2(maxDist * MathF.Cos(angle), maxDist * MathF.Sin(angle));
            float radius = float.MaxValue;

            // Ray-cast and find closest hit
            world.RayCast((fixt, hitPos, normal, fract) =>
            {
                radius = Math.Min(radius, fract * maxDist);
            }, pos, endPos);

            // Got any hit ?
            if (radius < float.MaxValue)
            {
                hit = radius;
                return true;
            }

            hit = 0.0f;
            return false;
        }

mikkleini avatar Nov 27 '21 12:11 mikkleini

Oh thanks a lot

Pastor111 avatar Nov 29 '21 16:11 Pastor111