質問

I'm creating a Ray Tracer in java and I just need to print out each of the three Spheres that I have made.

I created 3 sphere objects and stored them in an arraylist in my main which I am now passing to my camera so that I can create an image.

To do this I need to figure out:

  • If the intersection point isn't null, get the distance between the ray's origin and the intersection point.
  • If this is the first sphere in inner loop, set a variable to this distance – if not see if this distance is less than the previously measured distance – if so save this distance to compare to other spheres and set the index of the closest sphere to the index of the sphere being evaluated (the counter used in the inner loop going through the spheres).
  • Outside of this inner loop write the pixel back to the buffered image – but when calling localReflectionModel use the sphere that is closest (using the index of the closest sphere you saved in the inner loop).

Code:

for(int x = 0; x < filmResolutionX; x++) {

      for(int y =0; y < filmResolutionY; y++) {

          for (int z = 0; z < s.size(); z++) {

          double planeX = -0.5+ x / (double) filmResolutionX;
          double planeY = 0.5 - y / (double) filmResolutionY;
          double planeZ = 1;

          Coord3D planes = new Coord3D(planeX, planeY, planeZ);
          Coord3D Origin = new Coord3D(0,0,0);
          Ray plane = new Ray(Origin, planes);
          Coord3D iPoint = plane.intersectionPoint(s.get(z));
 Color colorSphere = new Color(0xD72448);
          if (iPoint != null){
             double distance = plane.getOrigin().distanceBetween(iPoint);
          }
          if (z == 0) {
             double distanceCheck1 = plane.getOrigin().distanceBetween(iPoint);
          } else if (z != 0) {

          }

          if (iPoint == null) {
              newImage.setRGB(x, y, 0);
          } else {
                colorSphere =  s.get(z).localReflectionModel(iPoint, l, plane);
              int rgb = colorSphere.getRGB();
              newImage.setRGB(x, y, rgb);

            }

            }

        }
    }

    return newImage;
    }
}

I am having problems trying to compare the distances from the previous spheres. When I try to reference the variables distance or distance check 1 I get an error saying that distance cannot be resolved to a variable

役に立ちましたか?

解決

It looks like you're having difficulties with scope. If you declare variables inside a block, like you do in the case of if (something) { double x = ...; }, the variables are visible only inside the declared block.

If you later want to access these variables, you have to change the scope so that they are visible in the block you want to use them in. Of course you could just declare them at the global level, but the art lies in finding the smallest effective scope.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top