Anyone familiar with the box2d haxe lib or can help me understand this code?


#1

Im trying to use the raycast function of B2World . I need to provide a “call back function” when I use it.

/**
	 * Ray-cast the world for all fixtures in the path of the ray. Your callback
	 * Controls whether you get the closest point, any point, or n-points
	 * The ray-cast ignores shapes that contain the starting point
	 * @param callback A callback function which must be of signature:
	 * <code>function Callback(fixture:B2Fixture,    // The fixture hit by the ray
	 * point:B2Vec2,         // The point of initial intersection
	 * normal:B2Vec2,        // The normal vector at the point of intersection
	 * fraction:Float       // The fractional length along the ray of the intersection
	 * ):Float
	 * </code>
	 * Callback should return the new length of the ray as a fraction of the original length.
	 * By returning 0, you immediately terminate.
	 * By returning 1, you continue wiht the original ray.
	 * By returning the current fraction, you proceed to find the closest point.
	 * @param point1 the ray starting point
	 * @param point2 the ray ending point
	 */
	public function rayCast(callbackMethod:B2Fixture -> B2Vec2 -> B2Vec2 -> Float -> Dynamic, point1:B2Vec2, point2:B2Vec2):Void
	{
		var broadPhase:IBroadPhase = m_contactManager.m_broadPhase;
		var output:B2RayCastOutput = new B2RayCastOutput ();
		function rayCastWrapper(input:B2RayCastInput, proxy:Dynamic):Float
		{
			var userData:Dynamic = broadPhase.getUserData(proxy);
			var fixture:B2Fixture = cast (userData, B2Fixture);
			var hit:Bool = fixture.rayCast(output, input);
			if (hit)
			{
				var fraction:Float = output.fraction;
				var point:B2Vec2 = new B2Vec2(
					(1.0 - fraction) * point1.x + fraction * point2.x,
					(1.0 - fraction) * point1.y + fraction * point2.y);
				return callbackMethod(fixture, point, output.normal, fraction);
			}
			return input.maxFraction;
		}
		var input:B2RayCastInput = new B2RayCastInput(point1, point2);
		broadPhase.rayCast(rayCastWrapper, input);
	}

So my code is:

m_world.rayCast(rcCallback, p1, p2);

and my callback function is:

private  function  rcCallback(fixture:B2Fixture, point:B2Vec2, normal:B2Vec2, fraction:Float):Float
	{
		if (fixture.getFilterData().groupIndex==-1)
		{
			return -1;
		}
		return fraction;
	}

I have never really done this type of thing with callbacks before so I don’t really understand.

but the function only returns void. I’m probably doing something wrong.


#2

This looks like it calls a function within a function, so the callback method is supposed to have a return value, but the parent method doesn’t have (or need?) a return.

Does this link help with understanding the return value of the callback?

http://www.box2d.org/forum/viewtopic.php?t=8037

I haven’t used rayCast in Box2D before