Eldarion
Eldarion

Reputation: 59

Moving circle using y = mx + b formula in C++

So I am writing a program which is moving circle through a line, I need the coordinates of line pixels, so I am using y = mx + b formula, but the coordinates of y don't change if I use x++, can anyone tell me what i am doing wrong?

Here is a part of my code, where i am using this formula:

void draw_picture(Canvas & canvas) {

srand((unsigned)time(0));

PairXY a(200,400);
PairXY b(300,100);
int o=20;
Line l(a,b);
double x=0;
Circle cir(a,o);
draw_circle(cir, canvas);
draw_line(l, canvas);

x=a.x;
for (int i=20; i>0; i--){

  x++;

  ///////

  double m = (b.y-a.y)/(b.x-a.x);
  double b1 = a.y - m * x;
  double y = m * x + b1; 

  ///////

  a.x=x;
  a.y=y;

  Circle cir1(a,o); 
  draw_circle(cir1, canvas);
 }  
}

Upvotes: 0

Views: 1094

Answers (3)

Cool_Coder
Cool_Coder

Reputation: 5073

i suggest you use parametric equation of line:

p1(x1, y1, z1) & p2(x2, y2, z2)

u shud know p1 & p2. now for any point p(x, y, z), use the parameter 't'.

t = p2 - p1;//this gives you 't'
p = p1 + t *(p2 -p1)//you know p1, p2, t...so get values of p.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258618

Since you didn't specify the types of the pair's x and y, my guess is that the line

double m = (b.y-a.y)/(b.x-a.x);

is causing the problem. If the two values are int, and the first is lower, it will always return 0. For m to be the actual value, you need an explicit cast to bool:

double m = (double)(b.y-a.y)/(b.x-a.x);

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182769

double m = (b.y-a.y)/(b.x-a.x);
double b1 = a.y - m * x;
double y = m * x + b1; 

C++ does not use what you do with a value to influence how the value is computed. The fact that you are assigning these values to doubles does not cause them to be computed as doubles. Since the math is on integers, you get integer math, which is definitely not what you want.

One fix:

double m = (b.y-a.y) / (double) (b.x-a.x);
double b1 = a.y - (double) m * x;
double y = m * (double) x + b1;

By forcing at least one parameter to be a double in each operation, you force the other to be promoted to a double as well and force the operation to be done on the doubles.

Note that the first line is only safe if y is a signed type. If not, (b.y-a.y) could underflow. In that case, you need (b.y - (double) a.y).

Upvotes: 1

Related Questions