我有以下用于在Java3D中捕获鼠标点击的代码。我希望最终能够点击场景中的对象并用鼠标移动它。
public void mouseClicked(MouseEvent e)
{
pickCanvas.setShapeLocation(e);
PickResult result = pickCanvas.pickClosest();
if (result == null) {
System.out.println("Nothing picked");
} else {
Primitive p = (Primitive)result.getNode(PickResult.PRIMITIVE);
Shape3D s = (Shape3D)result.getNode(PickResult.SHAPE3D);
if (p != null) {
System.out.println(p.getParent().getClass().getName());
} else if (s != null) {
System.out.println(s.getClass().getName());
} else{
System.out.println("null");
}
}
}// end of class Pick
点击某些对象的输出如下:
Wall3D
Floor3D
Carpet3D
javax.media.j3d.TransformGroup
javax.media.j3d.SharedGroup
javax.media.j3d.TransformGroup
这是因为我的Wall3D / Floor3D和Carpet3D仅由一个原语构成,例如:
Carpet3D:
public class Carpet3D extends Group{
public Carpet3D() {
this.createSceneGraph();
}
public void createSceneGraph() {
Appearance appearance = getCarpetAppearance();
int primitiveflags = Primitive.GENERATE_NORMALS + Primitive.GENERATE_TEXTURE_COORDS;
Box floorShape = new Box(1.7f, .015f, 2.3f,primitiveflags,appearance);
this.addChild(floorShape);
}
DinnerTable3D:
public class DinnerTable3D extends Group{
public DinnerTable3D() {
this.createSceneGraph();
}
public void createSceneGraph() {
Appearance appearance = getWoodenAppearance();
//Table TOP
int primitiveflags = Primitive.GENERATE_NORMALS + Primitive.GENERATE_TEXTURE_COORDS;
Box tableTop = new Box(1.2f, .035f, .8f,primitiveflags,appearance);
TransformGroup tableTopGroup = new TransformGroup();
tableTopGroup.addChild(tableTop);
this.addChild(tableTopGroup);
//Dinner Table Legs
Box tableLeg = new Box(0.06f,.72f,0.06f, primitiveflags,appearance);
SharedGroup dinnerTableLegs = new SharedGroup();
dinnerTableLegs.addChild(tableLeg);
//Leg 1
this.addChild(Main.setPositionOfObject(new Vector3f(-1.14f,-0.755f,-.74f), dinnerTableLegs));
//Leg 2
this.addChild(Main.setPositionOfObject(new Vector3f(1.14f,-0.755f,.74f), dinnerTableLegs));
//Leg 3
this.addChild(Main.setPositionOfObject(new Vector3f(1.14f,-0.755f,-.74f), dinnerTableLegs));
//Leg 4
this.addChild(Main.setPositionOfObject(new Vector3f(-1.14f,-0.755f,.74f), dinnerTableLegs));
}
}
有人知道我如何获得对我点击的任何对象的主要组的引用吗?
更新:
我有这个代码有效但看起来非常难看。当引用只有一个级别的对象时,将为更高级别抛出空指针...
public void mouseClicked(MouseEvent e)
{
pickCanvas.setShapeLocation(e);
PickResult result = pickCanvas.pickClosest();
if (result == null) {
System.out.println("Nothing picked");
} else {
Primitive p = (Primitive)result.getNode(PickResult.PRIMITIVE);
Shape3D s = (Shape3D)result.getNode(PickResult.SHAPE3D);
if (p != null) {
System.out.println("One parent: " + p.getParent().getClass().getName());
System.out.println("Two parent: " + p.getParent().getParent().getClass().getName());
System.out.println("Three parent: " + p.getParent().getParent().getParent().getClass().getName());
}