LucarioCodes wrote ...

2023/3/14

# triangles

LucarioCodes

2023/3/14

How do I draw a triangle Pixel by pixel? I'm trying to copy the flag of the Bahamas, but I can't figure the triangle out.
LucarioCodes

2023/3/14

```GreenfootImage bg = getBackground();
for(int x = ___; x<=___; x++)
{
for(int y = ___; y<= ___; y++)
{
bg.setColorAt(x, y, COLOR);
}
}```
(using this code)
danpost

2023/3/14

LucarioCodes wrote...
How do I draw a triangle Pixel by pixel? I'm trying to copy the flag of the Bahamas, but I can't figure the triangle out. << Code Omitted >>
After line 1, you want to create some local variable for the dimensions of the triangle:
```int h = bg.getHeight(); // height of image to place triangle on (base length of triangle)
int w = (int)(Math.sqrt(3) * h / 2); // width of triangle with a vertical left side (altitude of triangle)```
These values will be used multiple times in the code to follow., starting with the loop limits:
```for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{```
The test to check if a point is in the triangle would be:
`if (Math.abs(y - h / 2) * w < (w - x) * h / 2)`
It basically compares the ratio of x with w to the ratio of y with h/2. The absolute value is used to work on both top and bottom at the same time, as the triangle is symmetrical with respect to the horizontal center line. The divisors of the ratios were multiplied to both sides to eliminate division that would result in fractional values.
LucarioCodes

2023/3/16

I still don't understand it, how do I acculy make the triangle appear on screen?
danpost

2023/3/16

LucarioCodes wrote...
I still don't understand it, how do I acculy make the triangle appear on screen?
Simply:
```public MyWorld()
{
super(800, 400, 1);
GreenfootImage bg = getBackground();
int h = bg.getHeight();
int w = (int)(Math.sqrt(3) * h / 2);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
if (Math.abs(y - h / 2) * w < (w - x) * h / 2)
bg.setColorAt(x, y, Color.BLACK);
}
}
}
}```
LucarioCodes

2023/3/16

Oh, thanks, sorry, I'm new to greenfoot
danpost

2023/3/16

LucarioCodes wrote...
Oh, thanks, sorry, I'm new to greenfoot
Line 10 should end with an opening bracket -- {