Commit 9072b9dc authored by wildfirecode's avatar wildfirecode

1

parent 52ef2046
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-present, Egret Technology.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
/**
* Copyright (c) 2014,Egret-Labs.org
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Egret-Labs.org nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
declare module p2 {
......@@ -37,12 +38,10 @@ declare module p2 {
lowerBound?: number[];
});
containsPoint(point: number[]): boolean;
setFromPoints(points: number[][], position: number[], angle: number, skinSize: number): void;
copy(aabb: AABB): void;
extend(aabb: AABB): void;
overlaps(aabb: AABB): boolean;
overlapsRay(ray:Ray): number;
}
......@@ -51,12 +50,16 @@ declare module p2 {
static AABB: number;
static BOUNDING_CIRCLE: number;
static NAIVE: number;
static SAP: number;
static boundingRadiusCheck(bodyA: Body, bodyB: Body): boolean;
static aabbCheck(bodyA: Body, bodyB: Body): boolean;
static canCollide(bodyA: Body, bodyB: Body): boolean;
constructor(type: number);
type: number;
result: Body[];
world: World;
boundingVolumeType: number;
......@@ -67,71 +70,62 @@ declare module p2 {
}
export class NaiveBroadphase extends Broadphase {
export class GridBroadphase extends Broadphase {
aabbQuery(world: World, aabb: AABB, result: Body[]): Body[];
constructor(options?: {
xmin?: number;
xmax?: number;
ymin?: number;
ymax?: number;
nx?: number;
ny?: number;
});
xmin: number;
xmax: number;
ymin: number;
ymax: number;
nx: number;
ny: number;
binsizeX: number;
binsizeY: number;
}
export class Narrowphase {
export class NativeBroadphase extends Broadphase {
static findSeparatingAxis(c1:Convex, offset1:number[], angle1:number, c2:Convex, offset2:number[], angle2:number, sepAxis:number[]): boolean;
static getClosestEdge(c:Convex, angle:number, axis:number[], flip:boolean): number;
static projectConvexOntoAxis(convexShape:Convex, convexOffset:number[], convexAngle:number, worldAxis:number[], result:number[]): void;
}
export class Narrowphase {
contactEquationPool: ContactEquationPool;
contactEquations: ContactEquation[];
contactSkinSize: number;
enabledEquations: boolean;
frictionEquations: FrictionEquation[];
enableFriction: boolean;
slipForce: number;
frictionCoefficient: number;
frictionEquationPool: FrictionEquationPool;
frictionEquations: FrictionEquation[];
frictionRelaxation: number;
frictionStiffness: number;
surfaceVelocity: number;
reuseObjects: boolean;
resuableContactEquations: any[];
reusableFrictionEquations: any[];
restitution: number;
slipForce: number;
stiffness: number;
surfaceVelocity: number;
//官方不赞成使用的属性
relaxation: number;
frictionStiffness: number;
frictionRelaxation: number;
enableFrictionReduction: boolean;
contactSkinSize: number;
bodiesOverlap(bodyA: Body, bodyB: Body): boolean;
capsuleCapsule(bi: Body, si: Capsule, xi: number[], ai: number, bj: Body, sj: Capsule, xj: number[], aj: number): void;
circleCapsule(bi: Body, si: Circle, xi: number[], ai: number, bj: Body, sj: Line, xj: number[], aj: number): void;
circleCircle(bodyA: Body, shapeA: Circle, offsetA: number[], angleA: number, bodyB: Body, shapeB: Circle, offsetB: number[], angleB: number, justTest: boolean, radiusA?:number, radiusB?:number): void;
circleConvex(circleBody:Body, circleShape:Circle, circleOffset:number[], circleAngle:number, convexBody:Body, convexShape:Convex, convexOffset:number[], convexAngle:number, justTest:boolean, circleRadius:number): void;
circleHeightfield(bi:Body, si:Circle, xi:number[], bj:Body, sj:Heightfield, xj:number[], aj:number): void;
circleLine(circleBody:Body, circleShape:Circle, circleOffset:number[], circleAngle:number, lineBody:Body, lineShape:Line, lineOffset:number[], lineAngle:number, justTest:boolean, lineRadius:number, circleRadius:number): void;
circleParticle(circleBody:Body, circleShape:Circle, circleOffset:number[], circleAngle:number, particleBody:Body, particleShape:Particle, particleOffset:number[], particleAngle:number, justTest:boolean): void;
circlePlane(bi:Body, si:Circle, xi:number[], bj:Body, sj:Plane, xj:number[], aj:number): void;
collidedLastStep(bodyA: Body, bodyB: Body): boolean;
convexCapsule(convexBody:Body, convexShape:Convex, convexPosition:number[], convexAngle:number, capsuleBody:Body, capsuleShape:Capsule, capsulePosition:number[], capsuleAngle:number): void;
convexConvex(bi:Body, si:Convex, xi:number[], ai:number, bj:Body, sj:Convex, xj:number[], aj:number): void;
convexLine(convexBody:Body, convexShape:Convex, convexOffset:number[], convexAngle:number, lineBody:Body, lineShape:Line, lineOffset:number[], lineAngle:number, justTest:boolean): void;
createContactEquation(bodyA: Body, bodyB: Body): ContactEquation;
createFrictionEquation(bodyA: Body,bodyB: Body): FrictionEquation;
createFrictionFromContact(contactEquation: ContactEquation): FrictionEquation;
lineBox(lineBody:Body, lineShape:Line, lineOffset:number[], lineAngle:number, boxBody:Body, boxShape:Box, boxOffset:number[], boxAngle:number, justTest:boolean): void;
lineCapsule(lineBody:Body, lineShape:Line, linePosition:number[], lineAngle:number, capsuleBody:Body, capsuleShape:Capsule, capsulePosition:number[], capsuleAngle:number): void;
lineLine(bodyA:Body, shapeA:Line, positionA:number[], angleA:number, bodyB:Body, shapeB:Line, positionB:number[], angleB:number): void;
particleConvex(particleBody:Body, particleShape:Particle, particleOffset:number[], particleAngle:number, convexBody:Body, convexShape:Convex, convexOffset:number[], convexAngle:number, justTest:boolean): void;
particlePlane(particleBody:Body, particleShape:Particle, particleOffset:number[], particleAngle:number, planeBody:Body, planeShape:Plane, planeOffset:number[], planeAngle:number, justTest:boolean): void;
planeCapsule(planeBody:Body, planeShape:Circle, planeOffset:number[], planeAngle:number, capsuleBody:Body, capsuleShape:Particle, capsuleOffset:number[], capsuleAngle:number, justTest:boolean): void;
planeConvex(planeBody:Body, planeShape:Plane, planeOffset:number[], planeAngle:number, convexBody:Body, convexShape:Convex, convexOffset:number[], convexAngle:number, justTest:boolean): void;
planeLine(planeBody:Body, planeShape:Plane, planeOffset:number[], planeAngle:number, lineBody:Body, lineShape:Line, lineOffset:number[], lineAngle:number): void;
reset(): void;
createContactEquation(bodyA: Body, bodyB: Body, shapeA: Shape, shapeB: Shape): ContactEquation;
createFrictionFromContact(c: ContactEquation): FrictionEquation;
}
export class SAPBroadphase extends Broadphase {
axisIndex: number;
axisList: Body[];
aabbQuery(world: World, aabb: AABB, result: Body[]): Body[];
sortAxisList(a: Body[], axisIndex: number): Body[];
axisIndex: number;
}
......@@ -145,10 +139,11 @@ declare module p2 {
constructor(bodyA: Body, bodyB: Body, type: number, options?: {
collideConnected?: boolean;
wakeUpBodies?: boolean;
});
type: number;
equations: Equation[];
equeations: Equation[];
bodyA: Body;
bodyB: Body;
collideConnected: boolean;
......@@ -162,6 +157,8 @@ declare module p2 {
export class DistanceConstraint extends Constraint {
constructor(bodyA: Body, bodyB: Body, options?: {
collideConnected?: boolean;
wakeUpBodies?: boolean;
distance?: number;
localAnchorA?: number[];
localAnchorB?: number[];
......@@ -178,7 +175,7 @@ declare module p2 {
lowerLimit: number;
position: number;
setMaxForce(maxForce: number): void;
setMaxForce(f: number): void;
getMaxForce(): number;
}
......@@ -186,6 +183,8 @@ declare module p2 {
export class GearConstraint extends Constraint {
constructor(bodyA: Body, bodyB: Body, options?: {
collideConnected?: boolean;
wakeUpBodies?: boolean;
angle?: number;
ratio?: number;
maxTorque?: number;
......@@ -202,14 +201,14 @@ declare module p2 {
export class LockConstraint extends Constraint {
constructor(bodyA: Body, bodyB: Body, options?: {
collideConnected?: boolean;
wakeUpBodies?: boolean;
localOffsetB?: number[];
localAngleB?: number;
maxForce?: number;
collideConnected?: boolean;
});
localAngleB: number;
localOffsetB: number[];
localAngleB: number;
setMaxForce(force: number): void;
getMaxForce(): number;
......@@ -219,6 +218,8 @@ declare module p2 {
export class PrismaticConstraint extends Constraint {
constructor(bodyA: Body, bodyB: Body, options?: {
collideConnected?: boolean;
wakeUpBodies?: boolean;
maxForce?: number;
localAnchorA?: number[];
localAnchorB?: number[];
......@@ -226,23 +227,26 @@ declare module p2 {
disableRotationalLock?: boolean;
upperLimit?: number;
lowerLimit?: number;
collideConnected?: boolean;
});
localAnchorA: number[];
localAnchorB: number[];
localAxisA: number[];
lowerLimit: number;
position: number;
velocity: number;
lowerLimitEnabled: boolean;
motorEnabled: boolean;
upperLimitEnabled: boolean;
lowerLimit: number;
upperLimit: number;
upperLimitEquation: ContactEquation;
lowerLimitEquation: ContactEquation;
motorEquation: Equation;
motorEnabled: boolean;
motorSpeed: number;
position: number;
upperLimit: number;
upperLimitEnabled: boolean;
disableRotationalLock: boolean;
disableMotor(): void;
enableMotor(): void;
disableMotor(): void;
setLimits(lower: number, upper: number): void;
}
......@@ -250,29 +254,32 @@ declare module p2 {
export class RevoluteConstraint extends Constraint {
constructor(bodyA: Body, bodyB: Body, options?: {
collideConnected?: boolean;
wakeUpBodies?: boolean;
worldPivot?: number[];
localPivotA?: number[];
localPivotB?: number[];
maxForce?: number;
collideConnected?: boolean;
});
angle: number;
lowerLimit: number;
lowerLimitEnabled: boolean;
motorEnabled: boolean;
pivotA: number[];
pivotB: number[];
upperLimit: number;
motorEquation: RotationalVelocityEquation;
motorEnabled: boolean;
angle: number;
lowerLimitEnabled: boolean;
upperLimitEnabled: boolean;
lowerLimit: number;
upperLimit: number;
upperLimitEquation: ContactEquation;
lowerLimitEquation: ContactEquation;
disableMotor(): void;
enableMotor(): void;
getMotorSpeed(): number;
//官方不赞成使用了
disableMotor(): void;
motorIsEnabled(): boolean;
setLimits(lower: number, upper: number): void;
setMotorSpeed(speed: number): void;
getMotorSpeed(): number;
}
......@@ -294,6 +301,7 @@ declare module p2 {
constructor(bodyA: Body, bodyB: Body);
contactPointA: number[];
penetrationVec: number[];
contactPointB: number[];
normalA: number[];
restitution: number;
......@@ -301,6 +309,8 @@ declare module p2 {
shapeA: Shape;
shapeB: Shape;
computeB(a: number, b: number, h: number): number;
}
export class Equation {
......@@ -317,21 +327,26 @@ declare module p2 {
stiffness: number;
relaxation: number;
G: number[];
offset: number;
a: number;
b: number;
epsilon: number;
timeStep: number;
needsUpdate: boolean;
multiplier: number;
relativeVelocity: number;
enabled: boolean;
gmult(): number;
computeB(): number;
gmult(G: number[], vi: number[], wi: number[], vj: number[], wj: number[]): number;
computeB(a: number, b: number, h: number): number;
computeGq(): number;
computeGW(): number;
computeGWlambda(): number;
computeGiMf(): number;
computeGiMGt(): number;
addToWlambda(deltalambda: number): void;
addToWlambda(deltalambda: number): number;
computeInvC(eps: number): number;
update(): void;
update():void;
}
......@@ -339,7 +354,6 @@ declare module p2 {
constructor(bodyA: Body, bodyB: Body, slipForce: number);
contactEquations: ContactEquation;
contactPointA: number[];
contactPointB: number[];
t: number[];
......@@ -347,8 +361,9 @@ declare module p2 {
shapeB: Shape;
frictionCoefficient: number;
setSlipForce(slipForce: number): void;
setSlipForce(slipForce: number): number;
getSlipForce(): number;
computeB(a: number, b: number, h: number): number;
}
......@@ -360,23 +375,27 @@ declare module p2 {
angle: number;
computeGq(): number;
}
export class RotationalVelocityEquation extends Equation {
constructor(bodyA: Body, bodyB: Body);
computeB(a: number, b: number, h: number): number;
}
export class EventEmitter {
on(type: string, listener: Function, context?: any): EventEmitter;
on(type: string, listener: Function): EventEmitter;
has(type: string, listener: Function): boolean;
off(type: string, listener: Function): EventEmitter;
emit(event: any): EventEmitter;
}
/* remove by ladeng6666
export class ContactMaterialOptions {
friction: number;
......@@ -387,29 +406,37 @@ declare module p2 {
frictionRelaxation: number;
surfaceVelocity: number;
}
}*/
export class ContactMaterial {
constructor(materialA: Material, materialB: Material, options?: ContactMaterialOptions);
static idCounter: number;
id: number;
materialA: Material;
materialB: Material;
constructor(materialA: Material, materialB: Material, options?: {
friction?: number;
restitution?: number;
stiffness?: number;
relaxation?: number;
frictionStiffness?: number;
frictionRelaxation?: number;
surfaceVelocity?: number
}
);
friction: number;
restitution: number;
stiffness: number;
relaxation: number;
frictionStuffness: number;
frictionStiffness: number;
frictionRelaxation: number;
surfaceVelocity: number;
contactSkinSize: number;
surfaceVelocity: number
}
export class Material {
constructor(id: number);
static idCounter: number;
constructor(id?: number);
id: number;
......@@ -417,44 +444,39 @@ declare module p2 {
export class vec2 {
static add(out: number[], a: number[], b: number[]): number[];
static centroid(out: number[], a: number[], b: number[], c: number[]): number[];
static clone(a: number[]): number[];
static copy(out: number[], a: number[]): number[];
static create(): number[];
static crossLength(a: number[], b: number[]): number;
static crossVZ(out: number[], vec: number[], zcomp: number): number;
static crossZV(out: number[], zcomp: number, vec: number[]): number;
static dist(a: number[], b: number[]): number;
static distance(a: number[], b: number[]): number;
static div(out: number[], a: number[], b: number[]): number[];
static divide(out: number[], a: number[], b: number[]): number[];
static dot(a: number[], b: number[]): number;
static rotate(out: number[], a: number[], angle: number): void;
static rotate90cw(out: number[], a: number[]): number;
static centroid(out: number[], a: number[], b: number[], c: number[]): number[];
static create(): number[];
static clone(a: number[]): number[];
static fromValues(x: number, y: number): number[];
static getLineSegmentsIntersection(out: number[], p0: number[], p1: number[], p2: number[], p3: number[]): boolean;
static getLineSegmentsIntersectionFraction(p0: number[], p1: number[], p2: number[], p3: number[]): number;
static len(a: number[]): number;
static length(a: number[]): number;
static lerp(out: number[], a: number[], b: number[], t: number): void;
static mul(out: number[], a: number[], b: number[]): number[];
static copy(out: number[], a: number[]): number[];
static set(out: number[], x: number, y: number): number[];
static toLocalFrame(out: number[], worldPoint: number[], framePosition: number[], frameAngle: number): void;
static toGlobalFrame(out: number[], localPoint: number[], framePosition: number[], frameAngle: number): void;
static add(out: number[], a: number[], b: number[]): number[];
static subtract(out: number[], a: number[], b: number[]): number[];
static sub(out: number[], a: number[], b: number[]): number[];
static multiply(out: number[], a: number[], b: number[]): number[];
static negate(out: number[], a: number[]): number[];
static normalize(out: number[], a: number[]): number[];
static reflect(out: number[], vector: number[], normal: number[]): void;
static rotate(out: number[], a: number[], angle: number): void;
static rotate90cw(out: number[], a: number[]): void;
static mul(out: number[], a: number[], b: number[]): number[];
static divide(out: number[], a: number[], b: number[]): number[];
static div(out: number[], a: number[], b: number[]): number[];
static scale(out: number[], a: number[], b: number): number[];
static set(out: number[], x: number, y: number): number[];
static sqrDist(a: number[], b: number[]): number;
static distance(a: number[], b: number[]): number;
static dist(a: number[], b: number[]): number;
static squaredDistance(a: number[], b: number[]): number;
static sqrLen(a: number[]): number;
static sqrDist(a: number[], b: number[]): number;
static length(a: number[]): number;
static len(a: number[]): number;
static squaredLength(a: number[]): number;
static str(vec: number[]): string;
static sub(out: number[], a: number[], b: number[]): number[];
static subtract(out: number[], a: number[], b: number[]): number[];
static toGlobalFrame(out: number[], localPoint: number[], framePosition: number[], frameAngle: number): void;
static toLocalFrame(out: number[], worldPoint: number[], framePosition: number[], frameAngle: number): void;
static vectorToLocalFrame(out: number[], worldVector: number[], frameAngle: number): void;
static sqrLen(a: number[]): number;
static negate(out: number[], a: number[]): number[];
static normalize(out: number[], a: number[]): number[];
static dot(a: number[], b: number[]): number;
static str(a: number[]): string;
}
......@@ -477,23 +499,15 @@ declare module p2 {
* @class Body
* @constructor
* @extends EventEmitter
* @param {Array} [options.force]
* @param {Object} [options]
* @param {Number} [options.mass=0] 一个大于0的数字。如果设置成0,其type属性将被设置为 Body.STATIC.
* @param {Array} [options.position]
* @param {Array} [options.velocity]
* @param {Boolean} [options.allowSleep]
* @param {Boolean} [options.collisionResponse]
* @param {Number} [options.angle=0]
* @param {Number} [options.angularForce=0]
* @param {Number} [options.angularVelocity=0]
* @param {Number} [options.ccdIterations=10]
* @param {Number} [options.ccdSpeedThreshold=-1]
* @param {Array} [options.force]
* @param {Number} [options.angularForce=0]
* @param {Number} [options.fixedRotation=false]
* @param {Number} [options.gravityScale]
* @param {Number} [options.id]
* @param {Number} [options.mass=0] 一个大于0的数字。如果设置成0,其type属性将被设置为 Body.STATIC.
* @param {Number} [options.sleepSpeedLimit]
* @param {Number} [options.sleepTimeLimit]
* @param {Object} [options]
*
* @example
* // 创建一个刚体
......@@ -506,7 +520,7 @@ declare module p2 {
* });
*
* // 将一个圆形形状添加到刚体
* body.addShape(new Circle({ radius: 1 }));
* body.addShape(new Circle(1));
*
* // 将刚体加入 world
* world.addBody(body);
......@@ -532,7 +546,22 @@ declare module p2 {
static SLEEPY: number;
static SLEEPING: number;
constructor(options?);
constructor(options?: {
force?:number;
position?:number[];
velocity?:number;
allowSleep?:boolean;
collisionResponse?:boolean;
angle?:number;
angularForce?: number;
angularVelocity?: number;
ccdIterations?: number;
ccdSpeedThreshold?:number;
fixedRotation?:boolean;
gravityScale?:number;
id?:number;
mass?:number
});
/**
* 刚体id
......@@ -553,6 +582,18 @@ declare module p2 {
* @type {Array}
*/
shapes: Shape[];
/**
* 碰撞形状相对于刚体中心的偏移
* @property shapeOffsets
* @type {Array}
*/
//shapeOffsets: number[][];
/**
* 碰撞形状的角度变换
* @property shapeAngles
* @type {Array}
*/
//shapeAngles: number[];
/**
* 质量
* @property mass
......@@ -565,6 +606,7 @@ declare module p2 {
* @type {number}
*/
inertia: number;
invInertia: number;
/**
* 是否固定旋转
* @property fixedRotation
......@@ -687,6 +729,7 @@ declare module p2 {
* @default true
*/
allowSleep: boolean;
wantsToSleep: boolean;
/**
* Body.AWAKE,Body.SLEEPY,Body.SLEEPING之一
*
......@@ -717,93 +760,13 @@ declare module p2 {
* @default 1
*/
gravityScale: number;
/**
* The angular velocity of the body, in radians per second.
* @property angularVelocity
* @type {number}
*/
angularVelocity: number;
/**
* The inverse inertia of the body.
* @property invInertia
* @type {number}
*/
invInertia: number;
/**
* The inverse mass of the body.
* @property invMass
* @type {number}
*/
invMass: number;
/**
* The previous angle of the body.
* @property previousAngle
* @type {number}
*/
previousAngle: number;
/**
* The previous position of the body.
* @property previousPosition
* @type {Array}
*/
previousPosition: number[];
/**
* Constraint velocity that was added to the body during the last step.
* @property vlambda
* @type {Array}
*/
vlambda: number[];
/**
* Angular constraint velocity that was added to the body during last step.
* @property wlambda
* @type {Array}
*/
wlambda: number[];
/**
* The number of iterations that should be used when searching for the time of impact during CCD. A larger number will assure that there's a small penetration on CCD collision, but a small number will give more performance.
* @property {Number} ccdIterations
* @default 10
*/
ccdIterations: number;
/**
* If the body speed exceeds this threshold, CCD (continuous collision detection) will be enabled. Set it to a negative number to disable CCD completely for this body.
* @property {Number} ccdSpeedThreshold
* @default -1
*/
ccdSpeedThreshold: number;
/**
* Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this body will move through other bodies, but it will still trigger contact events, etc.
* @property collisionResponse
* @type {Boolean}
*/
collisionResponse: boolean;
/**
* Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y.
* @property fixedX
* @type {Boolean}
*/
fixedX: boolean;
/**
* Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X.
* @property fixedY
* @type {Boolean}
*/
fixedY: boolean;
/**
* How long the body has been sleeping.
* @property idleTime
* @type {Number}
*/
idleTime: number;
/**
* 与每个形状对应的显示对象
*/
displays: egret.DisplayObject[];
displays: any[];
userData: any;
updateSolveMassProperties(): void;
/**
* 设置刚体总密度
* @method setDensity
......@@ -873,9 +836,9 @@ declare module p2 {
* 相对于 world 中的一个点施加力
* @method applyForce
* @param {Array} force 力
* @param {Array} relativePoint 以物体中心点为基准的点
* @param {Array} worldPoint world 中的点
*/
applyForce(force: number[], relativePoint: number[]): void;
applyForce(force: number[], worldPoint: number[]): void;
/**
* Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions.
* Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before.
......@@ -895,6 +858,8 @@ declare module p2 {
* @param {number} dt
*/
sleepTick(time: number, dontSleep: boolean, dt: number): void;
getVelocityFromPosition(story: number[], dt: number): number[];
getAngularVelocityFromPosition(timeStep: number): number;
/**
* Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken.
* @method overlaps
......@@ -903,264 +868,38 @@ declare module p2 {
*/
overlaps(body: Body): boolean;
/**
* Moves the shape offsets so their center of mass becomes the body center of mass.
* @method adjustCenterOfMass
*/
// functions below was added by ladeng6666
angularVelocity: number;
toWorldFrame(out: number[], localPoint: number[]): void;
toLocalFrame(out: number[], worldPoint: number[]): void;
vectorToLocalFrame(out:number[],worldVector:number[]):void;
vectorToWorldFrame(out:number[],localVector:number[]):void;
adjustCenterOfMass(): void;
/**
* Apply damping.
* @method applyDamping
* @param {number} dt Current time step
*/
fromPolygon(vertices: number[][], options?: any): Body;
applyDamping(dt: number): void;
/**
* Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points.
* @method fromPolygon
* @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes.
* @param {Object} [options]
* @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
* @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself.
* @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
* @return {Boolean} True on success, else false.
*/
fromPolygon(path:number[][], options?: {
optimalDecomp?: boolean;
skipSimpleCheck?: boolean;
removeCollinearPoints?: boolean; // Boolean | Number
}): boolean;
/**
* Sets the force on the body to zero.
* @method setZeroForce
*/
setZeroForce(): void;
/**
* Transform a world point to local body frame.
* @method toLocalFrame
* @param {Array} out The vector to store the result in
* @param {Array} worldPoint The input world point
*/
toLocalFrame(out: number[], worldPoint: number[]): void;
/**
* Transform a local point to world frame.
* @method toWorldFrame
* @param {Array} out The vector to store the result in
* @param {Array} localPoint The input local point
*/
toWorldFrame(out: number[], localPoint: number[]): void;
/**
* Apply force to a body-local point.
* @method applyForceLocal
* @param {Array} localForce The force vector to add, oriented in local body space.
* @param {Array} localPoint A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass.
*/
applyForceLocal(localForce: number[], localPoint: number[]): void;
/**
* Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
* @method applyImpulse
* @param {Array} impulse The impulse vector to add, oriented in world space.
* @param {Array} relativePoint A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass.
*/
applyImpulse(impulse: number[], relativePoint: number[]): void;
/**
* Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
* @method applyImpulseLocal
* @param {Array} impulse The impulse vector to add, oriented in world space.
* @param {Array} relativePoint A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass.
*/
applyImpulseLocal(impulse: number[], relativePoint: number[]): void;
/**
* Get velocity of a point in the body.
* @method getVelocityAtPoint
* @param {Array} result A vector to store the result in
* @param {Array} relativePoint A world oriented vector, indicating the position of the point to get the velocity from
* @return {Array}
*/
getVelocityAtPoint(result: number[], relativePoint: number[]): number[];
/**
* Move the body forward in time given its current velocity.
* @method integrate
* @param {number} dt
*/
integrate(dt: number): void;
/**
* Transform a world point to local body frame.
* @method vectorToLocalFrame
* @param {Array} out The vector to store the result in
* @param {Array} worldVector The input world vector
*/
vectorToLocalFrame(out: number[], worldVector: number[]): void;
/**
* Transform a local point to world frame.
* @method vectorToWorldFrame
* @param {Array} out The vector to store the result in
* @param {Array} localVector The input local vector
*/
vectorToWorldFrame(out: number[], localVector: number[]): void;
}
/**
* Box shape class.
*
* @class Box
* @constructor
* @extends Convex
* @param {Object} [options] (Note that this options object will be passed on to the Shape constructor.)
* @param {Number} [options.width=1] Total width of the box
* @param {Number} [options.height=1] Total height of the box
*/
export class Box extends Convex {
constructor(options?: Object);
width: number;
height: number;
}
export class Pool {
objects: any[];
get(): Object;
release(object: Object): Pool;
resize(size: number): Pool;
}
export class OverlapKeeperRecordPool extends Pool {
}
export class IslandPool extends Pool {
}
export class IslandNodePool extends Pool {
}
export class ContactEquationPool extends Pool {
}
export class FrictionEquationPool extends Pool {
}
export class Ray {
static ALL: number;
static ANY: number;
static CLOSEST: number;
constructor(options?: {
from?: number[];
to?: number[];
checkCollisionResponse?: boolean;
skipBackfaces?: boolean;
collisionMask?: number;
collisionGroup?: number;
mode?: number;
callback?: number;
});
callback: Function;
checkCollisionResponse: boolean;
collisionGroup: number;
collisionMask: number;
direction: number[];
from: number[];
length: number;
mode: number;
skipBackfaces: boolean;
to: number[];
getAABB(aabb: AABB): void;
intersectBodies(bodies: Body[]): void;
update(): void;
}
export class RaycastResult {
body: Body;
faceIndex: number;
fraction: number;
isStopped: boolean;
normal: number[];
shape: Shape;
getHitDistance(ray: Ray): void;
getHitPoint(out:number[], ray: Ray): void;
hasHit():boolean;
reset(): void;
stop(): void;
}
export class TopDownVehicle {
constructor(chassisBody: Body, options?: Object);
chassisBody: Body;
wheels: WheelConstraint[];
addToWorld(world: World): void;
addWheel(wheelOptions?: Object): WheelConstraint;
removeFromWorld(world: World): void;
update(): void;
}
export class WheelConstraint extends Constraint {
constructor(vehicle: TopDownVehicle, options?: {
localForwardVector?: number[];
localPosition?: number[];
sideFriction?: number;
});
engineForce: number;
localForwardVector: number[];
localPosition: number[];
steerValue: number;
getSpeed(): number;
update(): void;
applyImpulse(force: number[], worldPoint: number[]): void;
collisionResponse: boolean;
fixedX: boolean;
fixedY: boolean;
}
export class Spring {
constructor(bodyA: Body, bodyB: Body, options?: {
stiffness?: number;
damping?: number;
localAnchorA?: number[];
localAnchorB?: number[];
worldAnchorA?: number[];
worldAnchorB?: number[];
});
stiffness: number;
damping: number;
bodyA: Body;
bodyB: Body;
damping: number;
stiffness: number;
applyForce(): void;
......@@ -1168,25 +907,15 @@ declare module p2 {
export class LinearSpring extends Spring {
constructor(bodyA: Body, bodyB: Body, options?: {
restLength?: number;
stiffness?: number;
damping?: number;
worldAnchorA?: number[];
worldAnchorB?: number[];
localAnchorA?: number[];
localAnchorB?: number[];
});
localAnchorA: number[];
localAnchorB: number[];
restLength: number;
setWorldAnchorA(worldAnchorA: number[]): void;
setWorldAnchorB(worldAnchorB: number[]): void;
getWorldAnchorA(result: number[]): void;
getWorldAnchorB(result: number[]): void;
getWorldAnchorA(result: number[]): number[];
getWorldAnchorB(result: number[]): number[];
applyForce(): void;
}
......@@ -1202,42 +931,18 @@ declare module p2 {
}
/**
* Capsule shape class.
*
* @class Capsule
* @constructor
* @extends Shape
* @param {Object} [options] (Note that this options object will be passed on to the Shape constructor.)
* @param {Number} [options.length=1] The distance between the end points
* @param {Number} [options.radius=1] Radius of the capsule
*/
export class Capsule extends Shape {
constructor(options?: Object);
constructor(optoins?: { length?: number; radius?: number });
length: number;
radius: number;
conputeMomentOfInertia(mass: number): number;
}
/**
* Circle shape class.
*
* @class Circle
* @constructor
* @extends Shape
* @param {Object} [options] (Note that this options object will be passed on to the Shape constructor.)
* @param {Number} [options.radius=1] The radius of this circle
* @example
* var circleShape = new Circle({ radius: 1 });
* body.addShape(circleShape);
*/
export class Circle extends Shape {
constructor(options?: Object);
constructor(options?: { radius: number });
/**
* 半径
......@@ -1248,44 +953,32 @@ declare module p2 {
}
/**
* Convex shape class.
*
* @class Convex
* @constructor
* @extends Shape
* @param {Object} [options] (Note that this options object will be passed on to the Shape constructor.)
* @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction.
* @param {Array} [options.axes] An array of unit length vectors, representing the symmetry axes in the convex.
* @example
* var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]];
* var convexShape = new Convex({ vertices: vertices });
* body.addShape(convexShape);
*/
export class Convex extends Shape {
static projectOntoAxis(offset: number[], localAxis: number[], result: number[]): void;
static triangleArea(a: number[], b: number[], c: number[]): number;
constructor(options?: Object);
constructor(options: { vertices: number[][]; axes?: number[][] });
vertices: number[][];
axes: number[];
centerOfMass: number[];
triangles: number[];
boundingRadius: number;
projectOntoLocalAxis(localAxis: number[], result: number[]): void;
projectOntoWorldAxis(localAxis: number[], shapeOffset: number[], shapeAngle: number, result: number[]): void;
updateCenterOfMass(): void;
updateTriangles(): void;
}
export class Heightfield extends Shape {
constructor(options?: {
heights?: number[];
heights: number[];
minValue?: number;
maxValue?: number;
elementWidth?: number;
elementWidth: number;
});
heights: number[];
......@@ -1293,21 +986,19 @@ declare module p2 {
minValue: number;
elementWidth: number;
getLineSegment(start:number[], end:number[], i:number): void;
updateMaxMinValues(): void;
}
export class Shape {
static BOX: number;
static CAPSULE: number;
static idCounter: number;
static CIRCLE: number;
static CONVEX: number;
static HEIGHTFIELD: number;
static LINE: number;
static PARTICLE: number;
static PLANE: number;
static CONVEX: number;
static LINE: number;
static Box: number;
static CAPSULE: number;
static HEIGHTFIELD: number;
constructor(options?: {
position?: number[];
......@@ -1319,32 +1010,27 @@ declare module p2 {
type?: number;
});
angle: number;
area: number;
body: Body;
type: number;
id: number;
boundingRadius: number;
collisionGroup: number;
collisionMask: number;
collisionResponse: boolean;
id: number;
material: Material;
position: number[];
area: number;
sensor: boolean;
type: number;
computeAABB(out: AABB, position: number[], angle: number): void;
//vertices: number[][]; //2015-05-12 ladeng6666
angle: number;
position: number[];
computeMomentOfInertia(mass: number): number;
raycast(result: RaycastResult, ray: Ray, position: number[], angle: number): void;
updateArea(): void;
updateBoundingRadius(): number;
updateArea(): void;
computeAABB(out: AABB, position: number[], angle: number): void;
}
export class Line extends Shape {
constructor(options?: {
length?: number;
});
constructor(option?: { length?: number });
length: number;
......@@ -1358,21 +1044,34 @@ declare module p2 {
}
export class Box extends Shape {
constructor(options: { width?: number; height?: number});
width: number;
height: number;
}
export class Solver extends EventEmitter {
constructor();
static GS: number;
static ISLAND: number;
constructor(options?: {}, type?: number);
type: number;
equations: Equation[];
equationSortFunction: Function; //Function | boolean
equationSortFunction: Equation; //Equation | boolean
solve(dy: number, world: World): void;
solveIsland(dy: number, island: Island): void;
sortEquations(): void;
addEquation(eq: Equation): void;
addEquations(eqs: Equation[]): void;
removeAllEquations(): void;
removeEquation(eq: Equation): void;
solve(dt: number, world: World): void;
solveIsland(dt: number, island: Island): void;
sortEquations(): void;
removeAllEquations(): void;
tolerance: number;
frictionIterations: number;
}
export class GSSolver extends Solver {
......@@ -1394,40 +1093,31 @@ declare module p2 {
export class OverlapKeeper {
constructor();
recordPool: OverlapKeeperRecordPool;
tick(): void;
setOverlapping(bodyA: Body, shapeA: Body, bodyB: Body, shapeB: Body): void;
bodiesAreOverlapping(bodyA: Body, bodyB: Body): boolean;
}
export class OverlapKeeperRecord {
constructor(bodyA: Body, shapeA: Shape, bodyB: Body, shapeB: Shape);
bodyA: Body;
bodyB: Body;
shapeA: Shape;
shapeB: Shape;
bodyA: Body;
bodyB: Body;
tick(): void;
setOverlapping(bodyA: Body, shapeA: Shape, bodyB: Body, shapeB: Body): void;
bodiesAreOverlapping(bodyA: Body, bodyB: Body): boolean;
set(bodyA: Body, shapeA: Shape, bodyB: Body, shapeB: Shape): void;
}
export class TupleDictionary {
data: Object;
data: number[];
keys: number[];
copy(dict: TupleDictionary): void;
getKey(id1: number, id2: number): string;
getByKey(key: number): number;
get(i: number, j: number): number;
getByKey(key: number): Object;
getKey(i: number, j: number): string;
set(i: number, j: number, value: number): number;
reset(): void;
set(i: number, j: number, value: number): void;
copy(dict: TupleDictionary): void;
}
......@@ -1446,9 +1136,9 @@ declare module p2 {
bodies: Body[];
reset(): void;
getBodies(): Body[];
getBodies(result: any): Body[];
wantsToSleep(): boolean;
sleep(): void;
sleep(): boolean;
}
......@@ -1456,12 +1146,9 @@ declare module p2 {
static getUnvisitedNode(nodes: Node[]): IslandNode; // IslandNode | boolean
constructor(options?: Object);
equations: Equation[];
islands: Island[];
nodes: IslandNode[];
islandPool: IslandPool;
nodePool: IslandNodePool;
visit(node: IslandNode, bds: Body[], eqs: Equation[]): void;
bfs(root: IslandNode, bds: Body[], eqs: Equation[]): void;
......@@ -1518,7 +1205,6 @@ declare module p2 {
*/
addBodyEvent: {
type: string;
body: Body;
};
/**
......@@ -1528,7 +1214,6 @@ declare module p2 {
*/
removeBodyEvent: {
type: string;
body: Body;
};
/**
......@@ -1538,7 +1223,6 @@ declare module p2 {
*/
addSpringEvent: {
type: string;
spring: Spring;
};
/**
......@@ -1591,6 +1275,7 @@ declare module p2 {
* @param {Shape} shapeB
* @param {Body} bodyA
* @param {Body} bodyB
* @param {Array} contactEquations
*/
endContactEvent: {
type: string;
......@@ -1636,23 +1321,9 @@ declare module p2 {
gravity?: number[];
broadphase?: Broadphase;
islandSplit?: boolean;
doProfiling?: boolean;
});
/**
* For keeping track of what time step size we used last step
* @property lastTimeStep
* @type {number}
*/
lastTimeStep: number;
overlapKeeper: OverlapKeeper;
/**
* If the length of .gravity is zero, and .useWorldGravityAsFrictionGravity=true, then switch to using .frictionGravity for friction instead. This fallback is useful for gravityless games.
* @property {boolean} useFrictionGravityOnZeroGravity
* @default true
*/
useFrictionGravityOnZeroGravity: boolean;
/**
* 所有 Spring
* @property springs
......@@ -1781,9 +1452,9 @@ declare module p2 {
/**
* 添加约束
* @method addConstraint
* @param {Constraint} constraint
* @param {Constraint} c
*/
addConstraint(constraint: Constraint): void;
addConstraint(c: Constraint): void;
/**
* 添加触点材料
* @method addContactMaterial
......@@ -1807,9 +1478,9 @@ declare module p2 {
/**
* 移除约束
* @method removeConstraint
* @param {Constraint} constraint
* @param {Constraint} c
*/
removeConstraint(constraint: Constraint): void;
removeConstraint(c: Constraint): void;
/**
* 使物理系统向前经过一定时间
*
......@@ -1827,16 +1498,16 @@ declare module p2 {
* 添加一个 Spring
*
* @method addSpring
* @param {Spring} spring
* @param {Spring} s
*/
addSpring(spring: Spring): void;
addSpring(s: Spring): void;
/**
* 移除一个 Spring
*
* @method removeSpring
* @param {Spring} spring
* @param {Spring} s
*/
removeSpring(spring: Spring): void;
removeSpring(s: Spring): void;
/**
* 添加一个 Body
*
......@@ -1864,14 +1535,14 @@ declare module p2 {
getBodyByID(id: number): Body;
/**
* 两个刚体之间禁用碰撞
* @method disableBodyCollision
* @method disableCollision
* @param {Body} bodyA
* @param {Body} bodyB
*/
disableBodyCollision(bodyA: Body, bodyB: Body): void;
/**
* 两个刚体之间启用碰撞
* @method enableBodyCollision
* @method enableCollision
* @param {Body} bodyA
* @param {Body} bodyB
*/
......@@ -1881,56 +1552,71 @@ declare module p2 {
* @method clear
*/
clear(): void;
/**
* Test if a world point overlaps bodies
* @method hitTest
* @param {Array} worldPoint Point to use for intersection tests
* @param {Array} bodies A list of objects to check for intersection
* @param {number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects.
* @return {Array} Array of bodies that overlap the point
*/
hitTest(worldPoint: number[], bodies: Body[], precision: number): Body[];
/**
* Ray cast against all bodies in the world.
* @method raycast
* @param {RaycastResult} result
* @param {Ray} ray
* @return {boolean} True if any body was hit.
* 获得克隆
* @method clone
* @return {World}
*/
raycast(result: RaycastResult, ray: Ray): boolean;
clone(): World;
/**
* Runs narrowphase for the shape pair i and j.
* @method runNarrowphase
* @param {Narrowphase} np
* @param {Body} bi
* @param {Shape} si
* @param {Array} xi
* @param {number} ai
* @param {Body} bj
* @param {Shape} sj
* @param {Array} xj
* @param {number} aj
* @param {number} mu
* [ladeng6666] 检测world中,与一组全局坐标点worldPoint,与一组刚体是否发生碰撞,并返回碰撞的刚体列表
* @param {Array} worldPoint 一组全局要检测的全局坐标点.
* @param {Array} bodies 要检测的刚体列表.
* @param {number} precision 检测的精确度.
*/
runNarrowphase(np:Narrowphase, bi:Body, si:Shape, xi:number[], ai:number, bj:Body, sj:Shape, xj:number[], aj:number, mu:number): void;
/**
* Set the relaxation for all equations and contact materials.
* @method setGlobalRelaxation
* @param {number} relaxation
hitTest(worldPoint: number[], bodies: Body[], precision?: number): Body[];
//functions below were added by ladeng6666
/*raycastAll(from: number[], to: number[], options: { collisionMask?: number; collisionGroup?: number; skipBackfaces?: boolean; checkCollisionResponse?:boolean}, callback: Function): void;
raycastAny(from: number[], to: number[], options: Object, result: RayCastResult): void;
raycastClosed(from: number[], to: number[], options: Object, callback: Function): void;
*/
setGlobalRelaxation(relaxation: number): void;
raycast(result: RaycastResult, ray: Ray);
}
export class RaycastResult {
constructor();
body: Body;
fraction: number;
shape: Shape;
faceIndex: number;
isStopped: boolean;
normal: number[];
/**
* Set the stiffness for all equations and contact materials.
* @method setGlobalStiffness
* @param {Number} stiffness
*/
setGlobalStiffness(stiffness: number): void;
getHitPoint(out:number[],ray:Ray):number[];
getHitDistance(ray:Ray): number;
hasHit(): boolean;
reset();
stop();
}
export class Ray {
static ANY: number;
static CLOSEST: number;
static ALL: number;
constructor(options?: {
to?: number[];
from?: number[];
mode?: number;
callback?: Function;
collisionMask?: number;
collisionGroup?: number;
checkCollisionResponse?: boolean;
skipBackfaces?: boolean;
direction?: number[];
length?: number;
});
to: number[];
from: number[];
mode: number;
callback: Function;
collisionMask: number;
collisionGroup: number;
checkCollisionResponse: boolean;
skipBackfaces: boolean;
direction: number[];
length: number;
}
}
No preview for this file type
......@@ -3,8 +3,14 @@ import { FACTOR } from "./consts";
export default class Ball extends p2.Body {
_skin: egret.DisplayObject;
setImpulse: boolean;
constructor() {
super({ mass: 10 });
this.type = p2.Body.DYNAMIC;
this.init();
}
init() {
private init() {
this._skin = addImage('ball_png');
this._skin.anchorOffsetX = this._skin.width / 2;
this._skin.anchorOffsetY = this._skin.height / 2;
......@@ -13,7 +19,7 @@ export default class Ball extends p2.Body {
const shape = new p2.Circle({ radius: radius });
this.addShape(shape);
this.mass = 1;
shape.collisionGroup = 2;//010与001为0,010与110为1
}
updateSkin() {
......
import { addImage } from "./utils";
import { FACTOR } from "./consts";
/**
* 被打的砖块
*/
export default class Brick extends p2.Body {
_skin: egret.DisplayObject;
constructor() {
super();
this.type = p2.Body.KINEMATIC;
this.init();
}
init() {
this._skin = addImage('rect1_png');
this._skin.anchorOffsetX = this._skin.width / 2;
this._skin.anchorOffsetY = this._skin.height / 2;
const width = this._skin.width / FACTOR;
const height = this._skin.height / FACTOR;
const shape = new p2.Box({ width: width, height: height });
this.addShape(shape);
shape.collisionMask = 6;//010与001为0,010与110为1
}
updateSkin() {
this._skin.x = this.position[0] * FACTOR;
this._skin.y = this.position[1] * FACTOR;
this._skin.rotation = this.angle * 180 / Math.PI;
}
get skin() { return this._skin }
}
\ No newline at end of file
import { addImage } from "./utils";
import Ball from "./Ball";
import World from "./World";
import { FACTOR } from "./consts";
import Brick from "./Brick";
export default class Gun extends egret.Sprite {
_root: egret.DisplayObjectContainer;
_world: World;
_line: egret.Bitmap;
_gun: egret.Bitmap;
vec: egret.Point
constructor(root: egret.DisplayObjectContainer, world: World) {
super();
this._root = root;
......@@ -14,18 +17,28 @@ export default class Gun extends egret.Sprite {
this.initUI();
}
fire() {
fire(vec: egret.Point) {
egret.Tween.get(this._gun)
.to({ scaleY: 0.6 }, 100)
.to({ scaleY: 1 }, 100);
this.addBall();
const ball = this.addBall();
ball.mass = 0;
this._world.bodies.forEach(body => {
if (body instanceof Brick) {
this._world.setMaterial(ball, body);
}
})
ball.applyImpulse([vec.x, vec.y], [0, 0]);
}
addBall() {
const ball = new Ball();
ball.init();
ball.position = [this.x / FACTOR, this.y / FACTOR];
ball.skin.x = this.x;
ball.skin.y = this.y;
this._world.addBody(ball);
this._root.addChild(ball.skin);
this._world.skin.addChild(ball.skin);
return ball;
}
enable() {
......@@ -39,10 +52,19 @@ export default class Gun extends egret.Sprite {
this.stage.once(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this);
}
onTouchEnd(): any {
onTouchEnd(e: egret.TouchEvent): any {
this.hideLine();
this.stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onTouchMove, this);
// this.fire();
const point = new egret.Point(e.stageX, e.stageY)
var pos = new egret.Point(point.x - this.x, point.y - this.y);
var angle: number = Math.atan2(pos.x, pos.y)
var dis: number = 10000;
var x: number = Math.ceil(Math.sin(angle) * dis);
var y: number = Math.ceil(Math.cos(angle) * dis);
const vec = new egret.Point(x, y);
this.vec = vec;
this.fire(vec);
}
onTouchMove(e: egret.TouchEvent) {
......
import { getResPath } from "./utils";
import Gun from "./Gun";
import World from "./World";
import Brick from "./Brick";
import { FACTOR } from "./consts";
export class Main extends eui.UILayer {
private _gun: Gun;
private _world: World;
protected createGameScene(): void {
this._world = new World(this);
this._world = new World();
this._gun = new Gun(this, this._world);
this._world.gun = this._gun;
this._world.skin = new egret.Sprite();
this.addChild(this._world.skin);
this.addChild(this._gun);
this._gun.x = this.stage.stageWidth >> 1;
this._gun.y = 100;
this._gun.enable();
setInterval(() => {
this._gun.fire();
}, 500);
this.updateBrickBody();
//添加游戏帧频事件
this.addEventListener(egret.Event.ENTER_FRAME, this.loop, this);
}
updateBrickBody(): void {
for (var i = 0; i < 1; i++) {
var brick = new Brick();
var x = this.stage.stageWidth >> 1;
var y = 1000;
brick.position = [x / FACTOR, y / FACTOR];
brick.updateSkin();
brick.angle = (-Math.random() * Math.PI / 4) + (Math.random() * Math.PI / 4);
this._world.skin.addChild(brick.skin);
this._world.addBody(brick);
}
}
protected createChildren(): void {
super.createChildren();
this.runGame().catch(e => {
......@@ -29,7 +48,7 @@ export class Main extends eui.UILayer {
}
loop() {
this._world.step(1);
this._world.step(1 / 60);
this._world.loop();
}
......
import Ball from "./Ball";
import Gun from "./Gun";
export default class World extends p2.World {
_root: egret.DisplayObjectContainer;
constructor(root: egret.DisplayObjectContainer, options?: any) {
material: p2.Material;//碰撞时的弹性变化
_skin: egret.DisplayObjectContainer;
gun: Gun;
constructor(options?: any) {
super(options);
this._root = root;
this.init();
}
protected onHitBegin(evt): void {
var ball: Ball;
if (evt.bodyA instanceof Ball) ball = evt.bodyA;
if (evt.bodyB instanceof Ball) ball = evt.bodyB;
if (ball && ball.mass == 0) {
ball.setImpulse = true;//可以设置给小球冲量
ball.mass = 200;
}
if (ball && ball.setImpulse) {
const vec = this.gun.vec;
ball.applyImpulse([vec.x * 2, vec.y], [0, 0]);
ball.setImpulse = false;
}
}
/**
* 设置刚体碰撞的弹性
* */
setMaterial(body1: p2.Body, body2: p2.Body): void {
body1.shapes[0].material = this.material;
body2.shapes[0].material = this.material;
var roleAndStoneMaterial = new p2.ContactMaterial(
this.material, this.material,
{ restitution: 0.7, friction: 0 });//弹性,摩擦力
this.addContactMaterial(roleAndStoneMaterial);
}
loop(): any {
this.bodies.forEach(body => {
if (body instanceof Ball) {
......@@ -17,6 +47,11 @@ export default class World extends p2.World {
}
init() {
this.gravity = [0, 10];
this.gravity = [0, 200];
this.material = new p2.Material(0);
this.on("beginContact", this.onHitBegin.bind(this));
}
set skin(val: egret.DisplayObjectContainer) { this._skin = val }
get skin() { return this._skin }
}
\ No newline at end of file
export const FACTOR = 30;
\ No newline at end of file
export const FACTOR = 1;
// export const FACTOR = 30;
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment