Using an open static field, good programming practice / fast?

I am programming a big game in Java and I am trying to optimize the code, but also so that the code is neat and well organized. Now I'm not sure if I should use a public static field for individual classes that have a couple of variables that are used by multiple instances.

For example, a class camera has an x ​​and y position that determines which part of the map the user is viewing and what needs to be displayed on the screen. I am currently comparing with 50,000 units, and I have the following options for drawing them.

1: Save the link to the camera instance in each device and call getX () and getY () when it needs to be drawn:

public void paint()   
{   
   paint(x - camera.getX(), y - camera.getY());  
}  

2: Put the camera coordinates as arguments for each block when it is drawn:

public void paint(int cameraX, int cameraY)  
{   
   paint(x - cameraX, y - cameraY);  
}

3: Make x and y variables for the static camera class:

public void paint()   
{   
   paint(x - Camera.x, y - Camera.y);  
}

What interests me is what is usually seen as the best solution and affects performance. Perhaps there are a few more ways to do this that I have not thought about?

Thank!

+5
source share
8 answers

I suggest you create a Painter class and do the following:

public void paint(Painter painter)  
{   
   painter.draw(x, y, unit_sprite);
}

Thus, devices do not need to worry about the existence of a camera. How it works. The unit just needs to know how to draw itself according to the global coordinate scheme, and the artist will understand how this relates to the actual coordinates of the screen.

Why is this a good idea?

  • , . .
  • . , , . , . , , , .
  • , , , , .

:

  • , . , - ? , , , .
  • , - . , , , - , , .
  • # 1, , . , .

:

. , , , , - ( , blitting ). , , , . , - , . 20 , , . , , , .

:

, ( ) , , . . , , , .

:

  • , .. x, y , , - . .
  • (, Painter) , , -.
+3

, . .

, - . , , , .

+2

, , :

  • , , , , . , JIT
  • - , , , concurrency (, , ?)
  • , , . , , , , .
+1

m.server vaule.

, .

+1

; , , , .

, , , , , , .

0

get/set , . , . , .

0

.

long startTime = System.currentTimeMillis();
for(int i=0; i<1000000; i++){
  // Call your code

}
System.out.println("Total time " + (System.currentTimeMillis() - startTime)  + " ms");

, JIT , . . , , , .

0

( Java-).

, , .

- , - .

: http://i.stack.imgur.com/WtSue.png

I tested every way 3 times. As you can see, the result is quite similar, with the exception of 130 to 210, I can not explain why.

0
source

All Articles