Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use Raycast? #32

Open
Pastor111 opened this issue Sep 19, 2021 · 4 comments
Open

How to use Raycast? #32

Pastor111 opened this issue Sep 19, 2021 · 4 comments
Labels
documentation Improvements or additions to documentation

Comments

@Pastor111
Copy link

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

@codingben
Copy link
Owner

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 😄

@Pastor111
Copy link
Author

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

@mikkleini
Copy link

@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;
        }

@Pastor111
Copy link
Author

Oh thanks a lot

@codingben codingben added the documentation Improvements or additions to documentation label Mar 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

3 participants