Question: Vector distance

Hello!

I just bought the jme3 book, and loving it very much.
I’m trying the code samples out and experimenting a bit.
But I’m stuck at something, and it’s confusing me, hope you guys can help me.

I have created a scene, and when I click on the mouse button, a spatial is added to the scene. I added a control to the spatial to move it.
I want to add extra functionality, that if the spatial has traveled a specific distance, it is remove from the scene.
But my distance calculation is always zero…

this is the logic in the control to move the spatial and print the distance.`
[java]@Override
protected void controlUpdate(float tpf) {
if (startLocation == null) {
startLocation = spatial.getWorldTranslation();
}

    spatial.move(shootDirection.normalize().mult(3*tpf));

    System.out.println("Distance traveled: " + startLocation.distance(spatial.getWorldTranslation()));
  }
[/java]

although the spacial is moving correctly, I always get this output:


[java]Jul 23, 2013 11:02:46 PM com.jme3.scene.Node attachChild
INFO: Child (fireball-geom-0) attached to this node (fireball-objnode)
Jul 23, 2013 11:02:46 PM com.jme3.scene.Node attachChild
INFO: Child (fireball-geom-0) attached to this node (Root Node)
Distance traveled: 0.0
Distance traveled: 0.0
Distance traveled: 0.0
Distance traveled: 0.0
Distance traveled: 0.0
…[/java]

for debugging purposes I also added a log of the spatial’s current location (spatial.getWorldTranslation()) and this also seems correct.

I probably made an error, or some concept is not yet fully clear to me.
I hope you fellow monkeys can help me out!

kr,
de_pol

You store a reference to the woldTranslation rather than copying it into your own vector. I’m not 100% sure but you may well be getting that same vector back every time after.

Try copying the result i.e. startLocation = spatial.getWorldTranslation().clone();

…Or just accumulate the distance travelled as a float each frame rather than calculating the length from the start position.

Yes, zarch is right. You are keeping a reference to the original world translation and that is what is being changed when you move the spatial. So distance() call is rather Zen because the spatial is always where it came from.

Hi,

thank you very much for the quick replies.
When I opened up my code this morning, I spotted the error immediatly. Although for being a professional java developer for 7 years, this gigantic error made me blush!
I’ll blame it on the heat here :wink:

anyway, thank you very much guys!

1 Like