Cannot Cast Spatial

Hi guys, I have a trouble. I have extended Spatial class and have named the new class as “PieceSpatial”. However, I cannot cast spatials to that new object. Here is a sample :

This is what I try :

[java]
private void drawPiece(Piece piece) {
PieceSpatial pieceMesh = (PieceSpatial) getPieceObject(piece);
pieceMesh.setOriginalMaterial(getPieceMaterial(piece.getColor()));
pieceMesh.setMaterial(pieceMesh.getOriginalMaterial());
pieceMesh.setLocalTranslation((float) (2 * piece.getX()) + 1, 0f, -((float) (2 * piece.getY()) + 1));
boardNode.attachChild(pieceMesh);

}

[/java]

It gives me that error :
[java]
“java.lang.ClassCastException: com.jme3.scene.Node cannot be cast to chessgame.view.elements.PieceSpatial”
at chessgame.view.SceneHandler.drawPiece(SceneHandler.java:86)
at chessgame.view.SceneHandler.drawPieceObjects(SceneHandler.java:81)
at chessgame.view.SceneHandler.drawChessSet(SceneHandler.java:69)
at chessgame.ChessGame.simpleInitApp(ChessGame.java:39)
at com.jme3.app.SimpleApplication.initialize(SimpleApplication.java:225)
at com.jme3.system.lwjgl.LwjglAbstractDisplay.initInThread(LwjglAbstractDisplay.java:130)
at com.jme3.system.lwjgl.LwjglAbstractDisplay.run(LwjglAbstractDisplay.java:207)
at java.lang.Thread.run(Thread.java:722)
[/java]

\nThis is my extended Spatial :
[java]
public abstract class PieceSpatial extends Spatial {

private Material originalMaterial;

public void setOriginalMaterial(Material material) {
    this.originalMaterial = material;
}

public Material getOriginalMaterial() {
    return originalMaterial;
}

}
[/java]

Please give the full stack trace, I can’t see where this exception is thrown.

ur getiing node from loader

1 Like

@gouessej I edited.
@erasit However, I can cast it to Spatial. PieceSpatial extends Spatial. What is the matter :confused: ?

erslt is right, getPieceObject(piece) returns a Node (probably from the loader) and you try to cast it to PieceSpatial. Node extends Spatial but PieceSpatial doesn’t extend Node.

2 Likes

You cannot cast ot stuff it is not.

Spatial is a spatial, your class extends it (bad behaviour btw you really should not do that)

So your class is a spatial and can be casted to one and back.
However not everything that is a spatial is your class, hence the cast exception.

The loader does not know of your manipulations and just loads a fine node/spatial that has absolutly nothing to do with your custom class.

1 Like

Thank you guys, I can see what is going on right now :wink: