Raycasting help?

Hello,

In my game, I'm trying to create a laser tripmine (think those green boxy things with the blue lasers in the original Half-Life). The basic idea is that when the player is within a certain distance of, and is facing, a PhysicsObject of type Obstacle, they can place the mine and it will "attach" to the Obstacle. The mine has a bit of a laser graphic sticking out of it that fades out. The mine will then detect if there is another Obstacle across from it within a certain distance; if there is, it draws an end piece of the laser from that point, also fading out, and pointing back at the mine.

I have some of this working already. I can place the mine (currently just anywhere I drop it), and it draws the end piece of the laser at whatever distance away I tell it. To solve the problem of detecting nearby Obstacles, I believe I need to use raycasting. I've been trying to follow Emanuele Feronato's tutorial on slicing objects with Box2D, since he uses raycasting to determine if an object is being "sliced", but I can't get it to work right.

Here is my code (I'm using the Citrus Engine, but it uses Box2D for all of its physics):
Code:
public function Tripmine(name:String, params:Object=null)
{
   params.view = "assets/img/tripmine.png";
   
   var distX:Number = params.x - Registry._gs.player.x;
   var distY:Number = params.y - Registry._gs.player.y;
   params.angle = Math.atan2(-distY, -distX);
   params.rotation = params.angle*Registry.rotateBy;
   
   params.damage = 8;
   params.static = true;
   
   trace("Creating tripmine");
   super(name, params);
   _laserMaxLength = 100;
   _laserSegmentStart = new V2(x+6, y);
   cos = Math.cos(angle);
   sin = Math.sin(angle);
   _laserSegmentEnd = new V2(x+_laserMaxLength*cos, y+_laserMaxLength*sin);
   
   //ray cast from start x,y
   //if Obstacle is <= max length of laser,
   //plot laser end
   //otherwise, do nothing
   
   spr = new Sprite();
   spr.addEventListener(Event.ENTER_FRAME, updateWorld);
   
   _world = new b2World(new V2(0,10));
   
   _laserLength = 100;
   if(_laserLength <= _laserMaxLength)
   {
      var _laserX:Number = x+_laserLength*cos;
      var _laserY:Number = y+_laserLength*sin;
      
      _laserSegmentIntersect = new V2(_laserX, _laserY);
      
      _laserEnd = new BulletLaser("laserEnd", {x: _laserSegmentIntersect.x, y: _laserSegmentIntersect.y, rotation: Math.atan2(distY, distX)*Registry.rotateBy});
      Registry._gs.add(_laserEnd);
   }
}//

private function laserFired(fixture:b2Fixture, point:b2Vec2, normal:b2Vec2, fraction:Number):Number
{
   trace("LASER FIRED CALLBACK");
   trace("intersection at x: "+point.x+", y: "+point.y);
   
   spr.removeEventListener(Event.ENTER_FRAME, updateWorld);
   return 1;
}

private function updateWorld(e:Event):void
{
   trace("update");
   _world.Step(1/30,10,10);
   _world.RayCast(laserFired, _laserSegmentStart, _laserSegmentEnd);
}//


The idea is that I would update _laserLength with the distance between the ray's start point and its intersection point with an Obstacle. Since the levels of my game are surrounded with Obstacles, it should hit one eventually (and they're small levels). Before, I didn't have the Sprite in there with the event listener, since I figured the raycast only needed to be called once. But I never got a response in the laserFired() callback, so I added the event listener; unfortunately, I'm still not getting anything from that function. The event listener just fires without ever stopping.

Am I implementing the raycast wrong? Is there something that I'm missing? Should I use something else instead? Can anyone tell me what I'm doing wrong?
Are all the x's and y's scaled to Box2D units (meters) or are they in pixels?
@jayther

Yeah, the x's and y's are automatically scaled. I pulled this from the Citrus Engine's PhysicsObject class:
Code:
public function get x():Number
{
   if (_body)
      return _body.GetPosition().x * _box2D.scale;
   else
      return _x * _box2D.scale;
}

[Property(value="0")]
public function set x(value:Number):void
{
   _x = value / _box2D.scale;
   
   if (_body)
   {
      var pos:V2 = _body.GetPosition();
      pos.x = _x;
      _body.SetTransform(pos, _body.GetAngle());
   }
}
   
public function get y():Number
{
   if (_body)
      return _body.GetPosition().y * _box2D.scale;
   else
      return _y * _box2D.scale;
}

[Property(value="0")]
public function set y(value:Number):void
{
   _y = value / _box2D.scale;
   
   if (_body)
   {
      var pos:V2 = _body.GetPosition();
      pos.y = _y;
      _body.SetTransform(pos, _body.GetAngle());
   }
}


I tried adjusting the segment vectors to scale as well, just in case, but neither multiplying or dividing by the Box2D scale changed anything:
Code:
_laserSegmentStart = new V2((x+6)*Registry.scale, y*Registry.scale);
cos = Math.cos(angle);
sin = Math.sin(angle);
_laserSegmentEnd = new V2((x+_laserMaxLength*cos)*Registry.scale, (y+_laserMaxLength*sin)*Registry.scale);


Registry.scale refers to GameState(CitrusEngine.getInstance()).box2D.scale

I still get no response from the callback.
the get x and get y returns the position in pixels, so what you want is in box2d units (and the scale is pixels-per-meter). So dividing by the scale should work, but as you said, you did try and it still didn't work (but you should divide by the scale anyhow; otherwise the raycast thinks it's in 100 meters rather than 100 pixels).

I have another question: is the TripMine class a class for each mine or the main class for the entire thing?

If it's a class for each mine, then it seems like the _world is a separate physics world from the rest of the game since you're initializing a new b2World in the _world variable (so each TripMine instance has its own world).
Okay, I've switched it back. For convenience, I'll copy/paste the whole class here:

Code:
package com.weapons.bullets
{
   import Box2DAS.Collision.Shapes.b2PolygonShape;
   import Box2DAS.Common.V2;
   import Box2DAS.Common.b2Vec2;
   import Box2DAS.Dynamics.b2Fixture;
   import Box2DAS.Dynamics.b2World;
   
   import com.Registry;
   
   import flash.display.Sprite;
   import flash.events.Event;

   public class BulletTripmine extends Bullet
   {
      /*
      - when placed, spawns at end of barrel, rotated to face towards player
      - can only be placed if player is within its radius to an obstacle (need sensor out of player to detect if facing/touching one?)
      - when placed, attaches to nearest object
      - collision box is only around mine
      - sensor is drawn across mine's laser for explodey purposes
      - OPTIONAL: if another obstacle is within a certain distance, places the other end of the laser on that obstacle, rotated back towards mine
         - sensor is extended from mine laser to other laser, and when touched, causes mine to explode
      */
      
      private var _laserSegmentStart:V2;
      private var _laserSegmentIntersect:V2;
      private var _laserSegmentEnd:V2;
      private var _laserEnd:BulletLaser;
      private var _laserMaxLength:Number;
      private var _laserLength:Number;
      private var _world:b2World;
      private var spr:Sprite;
      
      public function BulletTripmine(name:String, params:Object=null)
      {
         params.view = "assets/img/tripmine.png";
         
         var distX:Number = params.x - Registry._gs.player.x;
         var distY:Number = params.y - Registry._gs.player.y;
         params.angle = Math.atan2(-distY, -distX);
         params.rotation = params.angle*Registry.rotateBy;
         
         params.damage = 8;
         params.static = true;
         
         trace("Creating tripmine");
         super(name, params);
         _laserMaxLength = 100;
         _laserSegmentStart = new V2((x+6)/Registry.scale, y/Registry.scale);
         cos = Math.cos(angle);
         sin = Math.sin(angle);
         _laserSegmentEnd = new V2(((x/Registry.scale)+_laserMaxLength*cos), ((y/Registry.scale)+_laserMaxLength*sin));
         
         //ray cast from start x,y
         //if Obstacle is <= max length of laser,
         //plot laser end
         //otherwise, do nothing
         
         spr = new Sprite();
         //spr.addEventListener(Event.ENTER_FRAME, updateWorld);
         
         _world = new b2World(new V2(0, 0));
         _world.Step(1/30,10,10);
         _world.ClearForces();
         _world.RayCast(laserFired, _laserSegmentStart, _laserSegmentEnd);
         
         _laserLength = 100;
         if(_laserLength <= _laserMaxLength)
         {
            var _laserX:Number = (x/Registry.scale)+_laserLength*cos;
            var _laserY:Number = (y/Registry.scale)+_laserLength*sin;
            
            _laserSegmentIntersect = new V2(_laserX, _laserY);
            
            _laserEnd = new BulletLaser("laserEnd", {x: _laserSegmentIntersect.x, y: _laserSegmentIntersect.y, rotation: Math.atan2(distY, distX)*Registry.rotateBy});
            Registry._gs.add(_laserEnd);
         }
      }//
      
      private function laserFired(fixture:b2Fixture, point:b2Vec2, normal:b2Vec2, fraction:Number):Number
      {
         trace("LASER FIRED CALLBACK");
         trace("intersection at x: "+point.x+", y: "+point.y);
         
         //spr.removeEventListener(Event.ENTER_FRAME, updateWorld);
         return 1;
      }
      
      /*
         if (_inverted) {
            _weapon = new Weapon("weapon", {x:x - width, y:y, width:100, height:40});
         } else {
            _weapon = new Weapon("weapon", {x:x + width, y:y, width:100, height:40});
         }
         _ce.state.add(_weapon);
         
         _weapon.type = weaponKind;
         _weaponJointDef = new b2WeldJointDef();
         _weaponJointDef.Initialize(body, _weapon.body, body.GetWorldCenter());
         
         _weaponJoint = b2WeldJoint(_box2D._world.CreateJoint(_weaponJointDef));
         
         _weaponTimeoutID = setTimeout(endweaponState, _weaponDuration);
         _ce.sound.playSound("Jump", 1,0);
      */
      
      override protected function defineFixture():void
      {
         super.defineFixture();
         
         _fixtureDef.isSensor = true;
      }//
      
      override protected function createShape():void
      {
         _shape = new b2PolygonShape();
         var w:Number = 13/Registry.scale;
         var h:Number = 21/Registry.scale;
         b2PolygonShape(_shape).SetAsBox(-w/2, -h/2, new V2((w/2)-(2/Registry.scale), 0));
      }//
      
      /**********************************************************
       * UPDATE FUNCTIONS
       ***********************************************************/
      
      private function updateWorld(e:Event):void
      {
         trace("update");
         _world.Step(1/30,10,10);
         _world.RayCast(laserFired, _laserSegmentStart, _laserSegmentEnd);
         //_world.RayCast(laserFired, new V2(_laserSegmentStart.x/Registry.scale, _laserSegmentStart.y/Registry.scale), new V2(_laserSegmentEnd.x/Registry.scale, _laserSegmentEnd.y/Registry.scale));
         //_world.RayCast(laserFired, new V2(_laserSegmentStart.x*Registry.scale, _laserSegmentStart.y*Registry.scale), new V2(_laserSegmentEnd.x*Registry.scale, _laserSegmentEnd.y*Registry.scale));
      }//
      
      /**********************************************************
       * SIGNAL FUNCTIONS
       ***********************************************************/
      
      override protected function spawnEffect():void
      {
         //explosions, sparks, etc. are spawned here
      }//
   }
}


The tripmines are basically bullets (not Box2D bullets, but my own class) that don't move.

I was thinking that the _world is a separate thing each time, but that's because A) that's how Emanuele Feronato did it, so it seemed like the way to go, and B) I can't reference the Citrus Engine's implementation of _world in the GameState. It actually doesn't seem to get implemented at all, as far as I can tell. I'm not sure if it's a bug, bad programming, or intended. I've actually asked about it on the Citrus Engine forums, but that community is dead, so I don't expect a response. 🙁
I remember seeing Emanuele Feronato's slicing thing when it was first made (and the second time for Box2D 2.1a), and most of his examples are the entire code for the Flash program example, not individual classes for a specific effect. So only look at the specific code that actually does the effect.

Anyway, whenever you do "new b2World(gravity)", you're creating a new instance of a physics world. In the case for your code, each BulletTripmine instance has its own (empty!) physics world, which is why the laserFired function is never called.

I took a look at the citrus engine source, and it looks like PhysicsObject has a protected _box2D:Box2D variable (which can be accessed if PhysicsObject is a parent class somewhere along the way), and (according to the Box2D class) you can get the world by doing "_box2D.world".

So in your BulletTripmine, you can do this:
Code:
_world = _box2D.world;


And it should start working.
Hey, I hadn't noticed that before... Well I seem to be able to reference it, as you said, using _world = _box2D.world;. Unfortunately, I still get nothing from the callback.
The raycast needs to be done every frame if you want it to keep tracking until it hits something. The raycast is only done in the one time you call it.
Okay, I moved the raycasting call to the update function (overriding the one inherited from CitrusObject on down).

I do not get anything from the callback function no matter what I do. It also crashes seemingly randomly. I can run around the stage, and sometimes when I spawn a second tripmine (but not always the second), it crashes, pointing to the raycasting line as the culprit. Here's some example output:

Quote:
[SWF] Volumes:CHICLET:Flash:Projects:Zombiepalooza:zombiepalooza:bin:Main.swf - 1,496,767 bytes after decompression
loading level level1.lev
Creating tripmine
SEGMENT START x: 12.899999809265136, y: 11.333333015441895, END x: -22.419944301350228, y: 104.96340043861132
Creating tripmine
SEGMENT START x: 11.63333339691162, y: 12.333333015441895, END x: 110.86426372738701, y: 1.6801600788868054
Creating tripmine
SEGMENT START x: 11.899999809265136, y: 11.533333778381348, END x: 80.66551327333553, y: 83.94713047926649

Assertion failed: (0.0f <= lower && lower <= input.maxFraction), function RayCast, file ../Box2D/Collision/Shapes/b2PolygonShape.cpp, line 249.

[object AlchemyExit]
at Function/<anonymous>()
at Function/<anonymous>()
at Box2DAS.Dynamics::b2World/RayCast()[/Volumes/CHICLET/Flash/Projects/Zombiepalooza/zombiepalooza/engine/Box2DAS/Dynamics/b2World.as:113]
at com.weapons.bullets::BulletTripmine/update()[/Volumes/CHICLET/Flash/Projects/Zombiepalooza/zombiepalooza/src/com/weapons/bullets/BulletTripmine.as:117]
at com.citrusengine.core::State/update()[/Volumes/CHICLET/Flash/Projects/Zombiepalooza/zombiepalooza/engine/com/citrusengine/core/State.as:78]
at com.states::GameState/update()[/Volumes/CHICLET/Flash/Projects/Zombiepalooza/zombiepalooza/src/com/states/GameState.as:360]
at com.citrusengine.core::CitrusEngine/handleEnterFrame()[/Volumes/CHICLET/Flash/Projects/Zombiepalooza/zombiepalooza/engine/com/citrusengine/core/CitrusEngine.as:172]
Never mind, I gave up. Thanks for your help.

Original thread: https://box2d.org/forum/viewtopic.php?t=8413