在JavaFX中使用物理引擎JBox2D (二)

2014-11-24 11:33:11 · 作者: · 浏览: 27
gc.save();
gc.setFill(mColor);
gc.fillOval(getX(), getY(), getRaidus() * 2, getRaidus() * 2);
gc.restore();
}

@Override
public void update() {
setX(mBody.getPosition().x * RATE - getRaidus());
setY(mBody.getPosition().y * RATE - getRaidus());
}

public double getWidth(){
return 2 * getRaidus();
}

public double getHeight(){
return 2 * getRaidus();
}

public DoubleProperty radiusProperty(){
return radius;
}

public double getRaidus(){
return radius.get();
}

public void setRadius(double radius){
this.radius.set(radius);
}
}

import org.jbox2d.dynamics.Body;

import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Paint;

public class WCircleBody extends WBody {

protected DoubleProperty radius;

public WCircleBody(Body body, double radius, Paint color){
this.mBody = body;
this.radius = new SimpleDoubleProperty(radius);
this.mColor = color;
}

@Override
public void draw(GraphicsContext gc) {
gc.save();
gc.setFill(mColor);
gc.fillOval(getX(), getY(), getRaidus() * 2, getRaidus() * 2);
gc.restore();
}

@Override
public void update() {
setX(mBody.getPosition().x * RATE - getRaidus());
setY(mBody.getPosition().y * RATE - getRaidus());
}

public double getWidth(){
return 2 * getRaidus();
}

public double getHeight(){
return 2 * getRaidus();
}

public DoubleProperty radiusProperty(){
return radius;
}

public double getRaidus(){
return radius.get();
}

public void setRadius(double radius){
this.radius.set(radius);
}
}

这个继承于WBody,draw方法中根据x,y和半径,来绘制圆。在update方法中,将圆的图形位置设置为Body刚体的位置。由于刚体里的position是正中心的,所以我们需要自己进行计算左上角的位置。

然后创建一个矩形的WBody,叫WBoxBody。

[java
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Paint;

import org.jbox2d.dynamics.Body;

public class WBoxBody extends WBody {
public WBoxBody(double width,double height, Body body, Paint paint) {
this.mBody = body;
this.mColor = paint;
this.width = width;
this.height = height;
}

@Override
public void draw(GraphicsContext gc) {
gc.save();
gc.setFill(mColor);
gc.fillRect(getX(), getY(), getWidth(),getHeight());
gc.restore();
}

@Override
public void update() {
setX(mBody.getPosition().x * RATE - getWidth() / 2);
setY(mBody.getPosition().y * RATE - getHeight() / 2);
}

}

import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Paint;

import org.jbox2d.dynamics.Body;

public class WBoxBody extends WBody {
public WBoxBody(double width,double height, Body body, Paint paint) {
this.mBody = body;
this.mColor = paint;
this.width = width;
this.height = height;
}

@Override
public void draw(GraphicsContext gc) {
gc.save();
gc.setFill(mColor);
gc.fillRect(getX(), getY(), getWidth(),getHeight());
gc.restore();
}

@Override
public void update() {
setX(mBody.getPosition().x * RATE - getWidth() / 2);
setY(mBody.getPosition().y * RATE - getHeight() / 2);
}

}
同样的,WBoxBody里跟WCircleBody里类似。就不做过多解释了。

下面我们来新建一个类