box2d-netstandard
box2d-netstandard copied to clipboard
How to use Raycast?
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
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 😄
Ok, thanks for you time(and also nice project)
@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;
}
Oh thanks a lot