프로그래밍/JavaScript
PIXI.js, box2d 적용
SpiritLink
2018. 4. 3. 15:46
ECMA6 기준으로 클래스에서 현재 물리를 구현중
1. b2CircleDef와 같이 Shape 정의를 먼저한다.
this.ballSd1 = new b2CircleDef();
this.ballSd1.density = 1.0;
this.ballSd1.radius = 20;
this.ballSd1.restitution = 0.2;
this.ballSd1.localPosition.Set(-20, 0);
this.ballSd2 = new b2CircleDef();
this.ballSd2.density = 1.0;
this.ballSd2.radius = 20;
this.ballSd2.restitution = 0.2;
this.ballSd2.localPosition.Set(20, 0);
2. 클래스의 Body에 Shape를 추가한다.
this.circleBd = new b2BodyDef();
this.circleBd.linearDamping = 0.01;
this.circleBd.angularDamping = 0.01;
this.circleBd.AddShape(this.ballSd1);
this.circleBd.AddShape(this.ballSd2);
this.circleBd.position.Set(Device.app.screen.width / 2, Device.app.screen.height / 2 + 100);
3. World에서 Body 생성
this.rigidBody = Device.gamestate.CreateBody(this.circleBd);
4. Sprite의 x, y 좌표는 body의 m_position x, y 를 계속 반영시킨다.
this.sprite.x = this.rigidBody.m_position.x;
this.sprite.y = this.rigidBody.m_position.y;
5. 물체에 힘을 주고 싶다면 SetLinearVelocity, SetAngularVelocity 2개의 방법이 있다.
Angular는 float을 인자로, Linear는 b2Vec (벡터2)를 인자로 받는다.
물체가 일정시간 움직이지 않으면 WakeUp 시켜야 한다. (WakeUp하지 않을경우 m_force는 바뀌지만 반영되지 않음)
this.rigidBody.WakeUp();
this.rigidBody.SetLinearVelocity(new b2Vec2(-100, -200));