Method returning negative numbers seemingly at random
Hi everyone. I'm trying to write a game that involves balls colliding with each other, but I couldn't get them to go in the right directions. Here's what I've narrowed the problem down to:
The colliding balls are b1 and b2. First I gave assigned their velocities to variables:
Code :
double xvel1=b1.xvel();
double xvel2=b2.xvel();
double yvel1=b1.yvel();
double yvel2=b2.yvel();
As an experiment, I entered the following code:
Code :
System.out.print(b1.xvel()+" "+xvel1);
b1.setXVel(b1.xvel());
b1.setYVel(b1.yvel());
b2.setXVel(b2.xvel());
b2.setYVel(b2.yvel());
System.out.println(b1.xvel()+" ");
Here are the methods I used above:
Code :
public double xvel() {return xvel;}
public double yvel() {return yvel;}
public void setXVel(double xv1) {xvel=xv1;}
public void setYVel(double xv1) {xvel=xv1;}
The result of this SHOULD have been that I assigned each ball's velocity to itself.
According to the numbers that were printed, b1.xvel() and xvel1 were the same. But after
b1.setXVel(b1.xvel());
b1.setYVel(b1.yvel());
b2.setXVel(b2.xvel());
b2.setYVel(b2.yvel());
the value of b1.xvel() changed. Sometimes it was a slightly different number. Other times it was negative. When I took those lines away I didn't get this error, so those four lines are causing the problems.
Has anyone had problems like this before? Is there something deeply weird going on, or am I missing something simple?
Re: Method returning negative numbers seemingly at random
Quote:
Code java:
public void setYVel(double xv1) {xvel=xv1;}
Perhaps this is the problem? (notice the xvel instead of yvel)
Re: Method returning negative numbers seemingly at random
Not sure if this will fix your problem since you didn't provide full code, but it is an error at least.
Code java:
public void setXVel(double xv1) {xvel=xv1;}
public void setYVel(double xv1) {xvel=xv1;}
This code only lets you set the x velocity (xvel). So the method says you are setting the Y velocity, but it is in fact setting the X velocity.
This could be affecting your calculations later on.
Re: Method returning negative numbers seemingly at random
*DEEP SIGH*...
Thank you! I guess that was a copy-paste error. Everything is working perfectly now.