Page 1 of 1

using sin and cos

PostPosted: Fri May 16, 2014 3:29 pm
by tvz
Hello everyone
Can someone tell me how do you use sin and cos? How can i use these on canvas to draw objects?
A small tutorial can help. :)

Re: using sin and cos

PostPosted: Sat May 17, 2014 3:44 pm
by skydereign
tvz wrote:Hello everyone
Can someone tell me how do you use sin and cos? How can i use these on canvas to draw objects?
A small tutorial can help. :)

sin/cos are just two trig functions, so really they are just math. It so happens that sin/cos is very useful for shapes, such as circles and triangles. It's hard to teach one how to draw objects on canvas using them in that all really you just copy math functions. So I can tell you how to draw a circle for instance, but to use them to draw things you'd have to know the math behind the functions and what you personally want to do with it. Here's an example of drawing a sin wave.
Code: Select all
int i;
setpen(255, 255, 255, 0, 2);
for(i=0; i<width; i++)
{
    int sin_value = sin((double)i/width*(2*PI));
    putpixel(i, height/2 + height/2.0*sin_value);
}

And here's a circle.
Code: Select all
int i;
double radius = width/2;
setpen(255, 255, 255, 0, 2);

for(i=0; i<360; i++) // loops through angles 0-359 degrees
{
    double rad = degtorad(i); // convert i to radians
    int xp = radius*cos(rad); // get the x value of the circle at this angle
    int yp = radius*sin(rad); // get the y value of the circle at this angle

    putpixel(width/2 + xp, height/2 + yp); // place it in the center of the canvas
}

Re: using sin and cos

PostPosted: Mon May 19, 2014 8:47 am
by tvz
1. I understood the first program but it just draws a straight white line horizontally on the screen. :(
and
2. I think i should first complete the unit on radian in my math book to understand circle drawing.

btw thank you :)
+1

Re: using sin and cos

PostPosted: Mon May 19, 2014 4:32 pm
by skydereign
tvz wrote:1. I understood the first program but it just draws a straight white line horizontally on the screen. :(

Ah, that's due to an error on my part. It should be this.
Code: Select all
int i;
setpen(255, 255, 255, 0, 2);
for(i=0; i<width; i++)
{
    float sin_value = sin((double)i/width*(2.0*PI));
    putpixel(i, height/2 + height/2.0*sin_value);
}

The reason was due to the floating point value being cut off of the sin_value. Since sin returns numbers between -1 and 1 it was being cast to 0.