USensorTest.pas
上传用户:zkjn0718
上传日期:2021-01-01
资源大小:776k
文件大小:3k
- unit USensorTest;
- interface
- {$I ......SourcePhysics2D.inc}
- uses
- UMain, UPhysics2DTypes, UPhysics2D, SysUtils;
- type
- TSensorTest = class(TTester)
- public
- m_sensor: Tb2Shape;
- constructor Create; override;
- procedure Step(var settings: TSettings; timeStep: Float); override;
- end;
- implementation
- { TSensorTest }
- constructor TSensorTest.Create;
- var
- i: Integer;
- bd: Tb2BodyDef;
- sd: Tb2PolygonDef;
- cd: Tb2CircleDef;
- ground, body: Tb2Body;
- begin
- inherited;
- begin
- bd := Tb2BodyDef.Create;
- {$IFDEF OP_OVERLOAD}
- bd.position.SetValue(0.0, -10.0);
- {$ELSE}
- SetValue(bd.position, 0.0, -10.0);
- {$ENDIF}
- ground := m_world.CreateBody(bd);
- sd := Tb2PolygonDef.Create;
- sd.SetAsBox(50.0, 10.0);
- ground.CreateShape(sd);
- cd := Tb2CircleDef.Create;
- cd.isSensor := True;
- cd.radius := 5.0;
- {$IFDEF OP_OVERLOAD}
- cd.localPosition.SetValue(0.0, 20.0);
- {$ELSE}
- SetValue(cd.localPosition, 0.0, 20.0);
- {$ENDIF}
- m_sensor := ground.CreateShape(cd);
- end;
- begin
- cd := Tb2CircleDef.Create;
- cd.radius := 1.0;
- cd.density := 1.0;
- bd := Tb2BodyDef.Create;
- for i := 0 to 6 do
- begin
- {$IFDEF OP_OVERLOAD}
- bd.position.SetValue(-10.0 + 3.0 * i, 20.0);
- {$ELSE}
- SetValue(bd.position, -10.0 + 3.0 * i, 20.0);
- {$ENDIF}
- body := m_world.CreateBody(bd, False);
- body.CreateShape(cd, False);
- body.SetMassFromShapes;
- end;
- cd.Free;
- bd.Free;
- end;
- end;
- procedure TSensorTest.Step(var settings: TSettings; timeStep: Float);
- var
- i: Integer;
- other: Tb2Body;
- center, d: TVector2;
- begin
- inherited;
- // Traverse the contact results. Apply a force on shapes that overlap the sensor.
- for i := 0 to m_pointCount - 1 do
- with m_points[i] do
- begin
- if state = e_contactRemoved then
- Continue;
- if shape1 = m_sensor then
- other := shape2.GetBody
- else if shape2 = m_sensor then
- other := shape1.GetBody
- else
- Continue;
- center := m_sensor.GetBody.GetWorldPoint(Tb2CircleShape(m_sensor).m_localPosition);
- {$IFDEF OP_OVERLOAD}
- d := center - position;
- if d.SqrLength < FLT_EPSILON * FLT_EPSILON then
- Continue;
- d.Normalize;
- other.ApplyForce(100.0 * d, position);
- {$ELSE}
- d := Subtract(center, position);
- if SqrLength(d) < FLT_EPSILON * FLT_EPSILON then
- Continue;
- Normalize(d);
- other.ApplyForce(Multiply(d, 100.0), position);
- {$ENDIF}
- end;
- end;
- initialization
- RegisterTestEntry('Sensor Test', TSensorTest);
- end.