Reputation: 2288
I'm working on a particle engine, in Eclipse on Windows 7, and I have a problem I've never seen before. I have this in my code:
float start = startPosition.getY();
p.position.addTo(p.moveVector);
float end = startPosition.getY();
if(start != end){
System.out.println("hit");
}
And it does print hit quite often. The reason I did this was because startPosition was being changed and it was messing up my program.
I also went into the debugger and looked at the values when it printer hit, and I got this for end, all variables in position and moveVector: 1.0E-5 I have no idea what to make of that.
Here is my code.
Particle Emitter http://tinyurl.com/9ahwodx
Particle http://tinyurl.com/8rw979d
Vector 3f http://tinyurl.com/9do6v2k
The code in question is at the bottom of ParticleEmitter.
If you want to see or know anything else let me know, but I think that's all the relevant info.
Upvotes: 1
Views: 632
Reputation: 3753
Your particleEmiter constructor creates a bunch of Particle objects, with startPosition as the position for each.
Java passes things by reference [sharing objects (the object "references" are passed by value, so everyone shares the same object)], so each of your Particle instances refers to the same Vector3f object for their position.
When you do p.position.addTo(...), you're changing all of your Particle's positions, as well as startPosition.
You need to clone the position when calling the Particle constructor.
Edit:
Clone is just a term for "constructing a new object that has the same values". You can do this on a case by case basis by passing:
new Vector3f(startPosition.x, startPosition.y, startPosition.z)
instead of startPosition.
That's not very robust though, because if Vector3f were to gain some state, you'd need to update those calls. See Cloneable for an interface that would let you just call [Err, brain freeze]startPosition.clone()
instead.
Edit 2: Or as points out, put a constructor on Vector3f that takes a Vector3f parameter. Your code then becomes new Vector3f(startPosition)
when you're passing the position to the Particle constructor.
Upvotes: 6
Reputation: 19623
To answer your first question, 1.0E-5 is essentially zero.
Overall, I think your problem is that you're trying to compare float
variables for equality which is never a good thing. My guess is that the values aren't actually "changing", but rather each time you run the floating point approximation used for start
and end
are getting represented a bit differently. This would explain the behavior you're seeing where the same code seems to behave a bit differently each time.
Check this out for more details:
What's wrong with using == to compare floats in Java?
Upvotes: 2