• Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By akshayMore
      Hello,
      I am trying to make a GeometryUtil class that has methods to draw point,line ,polygon etc. I am trying to make a method to draw circle.  
      There are many ways to draw a circle.  I have found two ways, 
      The one way:
      public static void drawBresenhamCircle(PolygonSpriteBatch batch, int centerX, int centerY, int radius, ColorRGBA color) { int x = 0, y = radius; int d = 3 - 2 * radius; while (y >= x) { drawCirclePoints(batch, centerX, centerY, x, y, color); if (d <= 0) { d = d + 4 * x + 6; } else { y--; d = d + 4 * (x - y) + 10; } x++; //drawCirclePoints(batch,centerX,centerY,x,y,color); } } private static void drawCirclePoints(PolygonSpriteBatch batch, int centerX, int centerY, int x, int y, ColorRGBA color) { drawPoint(batch, centerX + x, centerY + y, color); drawPoint(batch, centerX - x, centerY + y, color); drawPoint(batch, centerX + x, centerY - y, color); drawPoint(batch, centerX - x, centerY - y, color); drawPoint(batch, centerX + y, centerY + x, color); drawPoint(batch, centerX - y, centerY + x, color); drawPoint(batch, centerX + y, centerY - x, color); drawPoint(batch, centerX - y, centerY - x, color); } The other way:
      public static void drawCircle(PolygonSpriteBatch target, Vector2 center, float radius, int lineWidth, int segments, int tintColorR, int tintColorG, int tintColorB, int tintColorA) { Vector2[] vertices = new Vector2[segments]; double increment = Math.PI * 2.0 / segments; double theta = 0.0; for (int i = 0; i < segments; i++) { vertices[i] = new Vector2((float) Math.cos(theta) * radius + center.x, (float) Math.sin(theta) * radius + center.y); theta += increment; } drawPolygon(target, vertices, lineWidth, segments, tintColorR, tintColorG, tintColorB, tintColorA); } In the render loop:
      polygonSpriteBatch.begin(); Bitmap.drawBresenhamCircle(polygonSpriteBatch,500,300,200,ColorRGBA.Blue); Bitmap.drawCircle(polygonSpriteBatch,new Vector2(500,300),200,5,50,255,0,0,255); polygonSpriteBatch.end(); I am trying to choose one of them. So I thought that I should go with the one that does not involve heavy calculations and is efficient and faster.  It is said that the use of floating point numbers , trigonometric operations etc. slows down things a bit.  What do you think would be the best method to use?  When I compared the code by observing the time taken by the flow from start of the method to the end, it shows that the second one is faster. (I think I am doing something wrong here ).
      Please help!  
      Thank you.  
    • By menyo
      I have a MongoDB db on a server operated by Kryonet. Obviously I need to be able to query the database from the client for adding, removing, requesting all kind of assets. Now I have written the code to request, add and remove fighters on the Kryonet network I am wondering if there is a better way to do this. I feel it's a bit repetitive, especially when I need to implement this for all other assets the player can own and other players assets when needed. The way I am currently approaching this is the same as my chat/lobby system which works great but I was wondering if anyone could see improvement on my code or a complete different way that is much more scalable perhaps.
       
      public class ClientAssets { public static final int FIGHTER_REQUEST = 1; public static final int FIGHTER_RESPONSE = 2; public static final int FIGHTER_ADD = 3; public static final int FIGHTER_REMOVE = 4; public static void Register(EndPoint endPoint) { Kryo kryo = endPoint.getKryo(); kryo.register(FighterRequest.class); kryo.register(FighterResponse.class); kryo.register(FighterAdd.class); kryo.register(FighterRemove.class); } static public abstract class AssetPacket { public int packetId; public AssetPacket() { } } /** * Packet to request all owned fighters */ public static class FighterRequest extends AssetPacket { public ObjectId playerId; public FighterRequest(ObjectId playerId) { packetId = FIGHTER_REQUEST; this.playerId = playerId; } public FighterRequest() { } } /** * Receiving fighter data from server */ public static class FighterResponse extends AssetPacket { public Fighter fighter; public boolean add; // Add or remove public FighterResponse(Fighter fighter, boolean add) { packetId = FIGHTER_RESPONSE; this.fighter = fighter; this.add = add; } public FighterResponse() { } } /** * Adds a fighter to player assets */ public static class FighterAdd extends AssetPacket { public ObjectId fighterTemplateID; public FighterAdd(ObjectId fighterTemplateID) { packetId = FIGHTER_ADD; this.fighterTemplateID = fighterTemplateID; } public FighterAdd() { } } /** * Removes fighter from assets. */ public static class FighterRemove extends AssetPacket { public ObjectId fighterId; public FighterRemove(ObjectId fighterId) { packetId = FIGHTER_REMOVE; this.fighterId = fighterId; } public FighterRemove() { } } } To elaborate a bit more, this code will communicate between client and server. When receiving a request on the server it will lookup the request in the database. The client will store it for displaying the assets. A specific thing I am unsure about is the FighterResponse.add boolean. I need to be able to remove and add fighters, I guess I am better off with a FighterAddResponse and a FighterRemove response so I will send one boolean less each time this packet is send. But this will create even more repetitive code.
    • By Sparsh Tyagi
      I recently released my first puzzle game for Android which is called here.
      It's a simple looking game which has 50 unique levels. Each level has its own logic and you have to find/make the word here in each level. There are also 3 hints per level just in case you get stuck.

      I have never made videos in my life before but here's a quick look at the game:
      The reviews so far have been great and now I wish to share it with you guys.
      I would love to have any feedback or suggestions or criticism. It will help a lot!

      Link: https://play.google.com/store/apps/details?id=com.techyonic.here

      Thank you!
       




    • By thelordposeidon
      Hey guys, I've been working on some marching cubes, and I've been having some weird issues that I really can't seem to understand. Basically the mesh isn't forming properly. Here are some screenshots and the code as it will show you the issue quicker than me describing it.

       
      As you can see the cube kinda forms but some areas are messed up, Here is the relevant code.
       
      package voxels; import java.util.ArrayList; import java.util.List; import javax.swing.plaf.basic.BasicTreeUI.TreeCancelEditingAction; import org.lwjgl.util.vector.Vector3f; import models.MarchingCubesCases; import toolbox.UniversalFunctions; public class MeshGenerator { private static int[][] vertexOffset = new int[][] { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, { 0, 1, 1 } }; private static float target = 0.5f; public static Voxel[][][] generateVoxels(int size) { Voxel[][][] voxels = new Voxel[size][size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { voxels[i][j][k] = new Voxel(VoxelMaterial.Grass); } } } return voxels; } public static MeshData generateMeshMarchingCubes(Voxel[][][] voxels) { List<Vector3f> verts = new ArrayList<Vector3f>(); List<Float> normals = new ArrayList<Float>(); List<Integer> indices = new ArrayList<Integer>(); List<Float> textureCoords = new ArrayList<Float>(); for (int x = 0; x < voxels.length; x++) { for (int y = 0; y < voxels.length; y++) { for (int z = 0; z < voxels.length; z++) { if (voxels[x][y][z].getMaterial() == VoxelMaterial.Air) { continue; } float[] cube = new float[8]; if (checkIfExpose(voxels, x, y, z, cube) == false) { continue; } MarchCube(new Vector3f(x, y, z), cube, verts, indices); normals.add(0f); normals.add(1f); normals.add(0f); textureCoords.add(0f); textureCoords.add(1f); } } } MeshData data = new MeshData(); data.setIndices(UniversalFunctions.intListToArray(indices)); data.setVertsFromVector3f(verts); data.setNormals(UniversalFunctions.floatListToArray(normals)); data.setTextureCoords(UniversalFunctions.floatListToArray(textureCoords)); return data; } private static boolean checkIfExpose(Voxel[][][] voxels, int x, int y, int z, float[] cube) { Voxel[] surroundingVoxels = getSurroundingVoxels(voxels, x, y, z); boolean bool = false; for (int i = 0; i < cube.length; i++) { cube[i] = 1; } if (surroundingVoxels[0].getMaterial().equals(VoxelMaterial.Air)) { cube[0] = 0; cube[1] = 0; cube[4] = 0; cube[5] = 0; bool = true; } if (surroundingVoxels[1].getMaterial().equals(VoxelMaterial.Air)) { cube[0] = 0; cube[3] = 0; cube[4] = 0; cube[7] = 0; bool = true; } if (surroundingVoxels[2].getMaterial().equals(VoxelMaterial.Air)) { cube[4] = 0; cube[5] = 0; cube[6] = 0; cube[7] = 0; bool = true; } if (surroundingVoxels[3].getMaterial().equals(VoxelMaterial.Air)) { cube[0] = 0; cube[1] = 0; cube[2] = 0; cube[3] = 0; bool = true; } if (surroundingVoxels[4].getMaterial().equals(VoxelMaterial.Air)) { cube[1] = 0; cube[2] = 0; cube[5] = 0; cube[6] = 0; bool = true; } if (surroundingVoxels[5].getMaterial().equals(VoxelMaterial.Air)) { cube[2] = 0; cube[3] = 0; cube[6] = 0; cube[7] = 0; bool = true; } return bool; } private static Voxel[] getSurroundingVoxels(Voxel[][][] voxels, int x, int y, int z) { int maxLength = voxels.length; List<Voxel> voxelList = new ArrayList<Voxel>(); if (y - 1 > 0 && y - 1 < maxLength) { voxelList.add(voxels[x][y - 1][z]); } else { voxelList.add(new Voxel(VoxelMaterial.Air)); } if (x - 1 > 0 && x - 1 < maxLength) { voxelList.add(voxels[x - 1][y][z]); } else { voxelList.add(new Voxel(VoxelMaterial.Air)); } if (z - 1 > 0 && z - 1 < maxLength) { voxelList.add(voxels[x][y][z - 1]); } else { voxelList.add(new Voxel(VoxelMaterial.Air)); } if (z + 1 > 0 && z + 1 < maxLength) { voxelList.add(voxels[x][y][z + 1]); } else { voxelList.add(new Voxel(VoxelMaterial.Air)); } if (x + 1 > 0 && x + 1 < maxLength) { voxelList.add(voxels[x + 1][y][z]); } else { voxelList.add(new Voxel(VoxelMaterial.Air)); } if (y + 1 > 0 && y + 1 < maxLength) { voxelList.add(voxels[x][y + 1][z]); } else { voxelList.add(new Voxel(VoxelMaterial.Air)); } return voxelList.toArray(new Voxel[voxelList.size()]); } // MarchCube performs the Marching Cubes algorithm on a single cube private static void MarchCube(Vector3f pos, float[] cube, List<Vector3f> vertList, List<Integer> indexList) { int i, j, vert, idx; int flagIndex = 0; float offset = 0.0f; Vector3f[] edgeVertex = new Vector3f[12]; for (int inter = 0; inter < 12; inter++) { edgeVertex[inter] = new Vector3f(); } // Find which vertices are inside of the surface and which are outside for (i = 0; i < 8; i++) { if (cube[i] <= target) { flagIndex |= 1 << i; } } // Find which edges are intersected by the surface int edgeFlags = MarchingCubesCases.cubeEdgeFlags[flagIndex]; // If the cube is entirely inside or outside of the surface, then there will be // no intersections if (edgeFlags == 0) return; // Find the point of intersection of the surface with each edge for (i = 0; i < 12; i++) { // if there is an intersection on this edge if ((edgeFlags & (1 << i)) != 0) { offset = GetOffset(cube[MarchingCubesCases.edgeConnection[i][0]], cube[MarchingCubesCases.edgeConnection[i][1]]); edgeVertex[i].x = pos.x + (vertexOffset[MarchingCubesCases.edgeConnection[i][0]][0] + offset * MarchingCubesCases.edgeDirection[i][0]); edgeVertex[i].y = pos.y + (vertexOffset[MarchingCubesCases.edgeConnection[i][0]][1] + offset * MarchingCubesCases.edgeDirection[i][1]); edgeVertex[i].z = pos.z + (vertexOffset[MarchingCubesCases.edgeConnection[i][0]][2] + offset * MarchingCubesCases.edgeDirection[i][2]); } } // Save the triangles that were found. There can be up to five per cube for (i = 0; i < 5; i++) { if (MarchingCubesCases.triangleConnectionTable[flagIndex][3 * i] < 0) { break; } idx = vertList.size(); for (j = 0; j < 3; j++) { vert = MarchingCubesCases.triangleConnectionTable[flagIndex][3 * i + j]; indexList.add(idx + MarchingCubesCases.windingOrder[j]); vertList.add(edgeVertex[vert]); } } } // GetOffset finds the approximate point of intersection of the surface // between two points with the values v1 and v2 private static float GetOffset(float v1, float v2) { float delta = v2 - v1; return (delta == 0.0f) ? 0.5f : (target - v1) / delta; } } I can attach the look up tables if needed. The MeshData class is just a class to hold verts, indices, etc. The voxel data is generated using the generateVoxels method and it is for a size of 16. Finally the voxel material only maters if the material is air as then the voxel will need to be rendered. Any help would be amazing.
      Thanks
      Euan
  • Advertisement
  • Advertisement
Sign in to follow this  

Methods accessing each others variables

Recommended Posts

Hi guys,

So I'm wondering why cant I reference a value or even access a value that's in a method from another method.. like so

 

public class Main {

    public static void main(String arg[])
    {
                
        String bob = "bobby";
        compute();
    }

    public static void compute() 
    {
    main.bob = "yoyo";
    
    }
}


 

I don't know if I'd ever want to do this, but I'm just curious, does this mean that there's simply no other way to modify the variable values of a method without providing it with values through invoking the method ?  

 

So in the following way I can basically set what values (true to the predefined data types) these argument variables will have..

public class Main {

    public static void main(String arg[])
    {
        
        String one = "Ping",two = "Pong";
        String Result = "";
        Result = compute( one,  two);
        System.out.println(Result);
    }

    public static  String compute(String first, String second) 
    {
        
        String joined = first + " " + second;
    return (joined);
    
    }
}

 

What if instead of this I have

 

        String joined = first + " " + second;

        String joined_2 = third + " " + forth;

        String Altogether = joined + joined_2;
    return (Altogether);

 

So say i get to the first line in that code and suddenly want to change a value in the second line, would that be possible ? 

 

Okay crappy example, I suppose parameters are then the only manner available for methods to get values from the invoking method ? 

 

Share this post


Link to post
Share on other sites
Advertisement

Most languages (including C# of Java, which you appear to maybe be using) are not designed this way; they simply don't consider a method to have local instance variables and state associated with it that persists outside the temporary memory reserved for that method when it is executing. In fact, I don't know any languages (offhand) that would explicitly permit you to do what you wrote the initial example for.

Some languages do have "static" local variables in methods, but they're usually just like globals with a narrower lexical scope; explicitly narrowed so you cannot refer to them like you're suggesting.

So yes, there's no way to modify the value of a variable in a method without passing a value to that method (or similar) to indicate how the method should initialize the variable. The (non-static) variables you're declaring in a method are local: they come into being when the method is called, and exist only for the duration of the method's execution. Then they are (effectively) destroyed when the method ends. So there's nothing to "modify" outside that method.

45 minutes ago, Xer0botXer0 said:

Okay crappy example, I suppose parameters are then the only manner available for methods to get values from the invoking method ? 

 

If you want to "share" information you need to either pass it from method to method or store it as a member of the containing class. Those are generally your two best options, and there are cases where either choice is the better one. It depends on what you're doing.

You can also create globals and share information that way, but this is generally not a great option (and not directly supported by C#, but you can do things to create effective globals that share all the same problems anyhow).

Share this post


Link to post
Share on other sites

Thanks, well I'm using Java. And I was thinking of objects in Game Makers GML, where variables of objects can be referenced  and modified.

But I've come to realize that methods in Java are similar to Scripts in GML which are temporary. So what I'm looking for I think would be classes. I recall now that I can access variables/arrays and such from one class to another using the classname.variablename line. 

I'm mainly trying to get a better image of what everything can and cant do while studying. 

Share this post


Link to post
Share on other sites
18 minutes ago, Xer0botXer0 said:

Thanks, well I'm using Java. And I was thinking of objects in Game Makers GML, where variables of objects can be referenced  and modified.

 

Variables stored in objects can be referenced and modified in Java. Methods, however, are not objects in that sense.

19 minutes ago, Xer0botXer0 said:

So what I'm looking for I think would be classes. I recall now that I can access variables/arrays and such from one class to another using the classname.variablename line. 

Yes. A class describes a type of object, and you can create instances of that type. Those instances are the kinds of objects you can read and write the member variables of.

Share this post


Link to post
Share on other sites

So I did a bit of further reading and from what I can see, There are Instance fields/Instance methods and there are Class fields/Class methods, The class fields and methods are unique to each instance(object) of a class. Where Class fields and methods are somewhat global and are recognized by their static modifier in their definition. 

I can modify the instance fields/methods by storing a reference to the object in a variable.

But I've got a question regarding the Static types, I'm going to test this out now anyway for the practice because as someone said before it helps to try it out myself too. But I like the forum since you can sometimes get more information which is apart of what helped me progress in Java quite a bit. 

If I create a class called Fruit, and within the class I create a class variable called fruit_Type, then create four objects of class Fruit, I don't use a for loop rather just one after another, in each case I set the fruit_Type class variable to something different like "mango", "orange", "tomato(is tomato a fruit lol)", "guava". 

If I then iterate through all four objects, will they have unique values for fruit_Type, can I even access a static field(var) that way ? Going to test this out now. 

 

From my understanding the purpose of a class field is to store a value that all objects of that class will share, the purposes of instance fields is that the instance values can be unique, instead of having a basket.java of mangoes I'd have a basket of a variety of fruit.

 

Okay I tested it.

public class Main {
    
    public static void main(String arg[])
    {
        
        Fruit f1 = new Fruit();
        f1.fruit_Types = "Banana";
        
        System.out.println(f1.fruit_Types);
        System.out.println("");
        
        Fruit f2 = new Fruit();
        f2.fruit_Types = "Guava";
        
        System.out.println(f1.fruit_Types);
        System.out.println(f2.fruit_Types);
        System.out.println("");
        Fruit f3 = new Fruit();
        f3.fruit_Types = "Grape";
        
        System.out.println(f1.fruit_Types);
        System.out.println(f2.fruit_Types);
        System.out.println(f3.fruit_Types);
        System.out.println("");
    }
}

 

Fruit.java :: public static String fruit_Types = "Lemon"; produces:

  • Banana
  •  
  • Guava
  • Guava
  •  
  • Grape
  • Grape
  • Grape

while without the static modifier it becomes an instance field and produces:

  • Banana
  •  
  • Banana
  • Guava
  •  
  • Banana
  • Guava
  • Grape

 

So I'm happy with the findings. :D

Edited by Xer0botXer0

Share this post


Link to post
Share on other sites

Static, in this context, does mean "shared across all instances of this class". Everything else has its own copy per instance. Good work on testing for yourself and verifying your understanding. Try and avoid statics unless you absolutely need something shared, however.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Advertisement