Using triple int array - java

Okay, so i created an an int array like so int position = new int[160][250][160] to represent a possition in a 3D space ([x][y][z]) what i want to do is draw a line from one point to another, but am confused about how to get a number from that array?
if i want to draw a line from point [78][89][30] to [34][75][25] how would i get a specific number from just one of those arrays? or would it be best just to create 3 seperate arrays? (keeping voxels in mind)?
Thanks - Shamus

I would suggest to have a class 3DPoint
class Point3D{
int x;
int y;
int z;
}
class Line{
Point3D pointFrom;
Point3D pointTo;
}
This is how you do things easily in Object Oriented World

Related

Creating a large 2D array and populating it from a LinkedHashMap of smaller 2D Arrays

I'm trying to create a large 2D Array int[][] from a LinkedHashMap which contains a number of smaller Arrays for an A* Pathfinder I'm working on.
The Map the Pathfinder is using is streamed in smaller chunks to the client and converted into a simplified version for the Pathfinder.
Map<Coord, int[][]> pfmapcache = new LinkedHashMap<Coord, int[][]>(9, 0.75f, true);
The Coord look like this: Coord(0,0) or Coord(-1,0).... etc. and the int[][] are always int[100][100] big.
Now I would like to create a new large int[][] that would encompass all the smaller Array where the small Array Coord(0,0) would be in the center of the new Large Array.
int[][] largearray = [-1,1][0,1][1,1]
[-1,0][0,0][1,0]
[-1,-1][0,-1][1,-1]
So that the large array would be int[300][300] big in this example.
2. I would like to expand the new large Array if a new small array gets added to the pfmapcache.
int[][] largearray = [][][1,2]
[-1,1][0,1][1,1]
[-1,0][0,0][1,0]
[-1,-1][0,-1][1,-1]
I don't have to store the smaller Arrays in pfmapcache I could add them as they are created with a 2 small arrays combining etc.. but with the negative Position of the Arrays in relation to the original I have no idea how to combine them and preserve their relative postion.
First time posting here, if I need to clarify something pls let me know.
You're wondering how to use your existing pathfinder algo with a chunked map.
This is when you need to place an abstraction layer between your data representation, and your data usage (like a Landscape class).
Q: Does a pathfinding algorithm need to know it works on a grid, on a chunked grid, on a sparse matrix, or on a more exotic representation?
A: No. A Pathfinder only needs to know one thing: 'Where can I get from here?'
Ideally
you should drop any reference to the fact that your world is on a grid by working with only a class like:
public interface IdealLandscape {
Map<Point, Integer> neighbours(Point location); // returns all neighbours, and the cost to get there
}
Easy alternative
However I understood your existing implementation 'knows' about grids, with the added value that adjacency is implicit and you're working with points as (x, y). You however lost this when introducing chunks, so working with the grid doesn't work anymore. So let's make the abstraction as painless as possible. Here's the plan:
1. Introduce a Landscape class
public interface Landscape {
public int getHeight(int x, int y); // Assuming you're storing height in your int[][] map?
}
2. Refactor your Pathfinder
It's reaaally easy:
just replace map[i][j] with landscape.getHeight(i, j)
3. Test your refactoring
Use a very simple GridLandscape implementation like:
public class GridLandscape implements Landscape {
int[][] map;
public GridLandscape(...){
map = // Build it somehow
}
#Override
public int getHeight(int x, int y){
return map[x][y]; // Maybe check bounds here ?
}
}
4. Use your ChunkedGridLandscape
Now your map is abstracted away, and you know your Pathfinder works on it, you can replace it with your chunked map!
public class ChunkedGridLandscape implements Landscape {
private static final int CHUNK_SIZE = 300;
Map<Coord, int[][]> mapCache = new LinkedHashMap<>(9, 0.75f, true);
Coord centerChunkCoord;
public ChunkedGridLandscape(Map<Coord, int[][]> pfmapcache, Coord centerChunkCoord){
this.mapCache = pfmapcache;
this.centerChunkCoord = centerChunkCoord;
}
#Override
public int getHeight(int x, int y){
// compute chunk coord
int chunkX = x / CHUNK_SIZE - centerChunkCoord .getX();
int chunkX = y / CHUNK_SIZE - centerChunkCoord .getY();
Coord chunkCoord = new Coord(chunkX, chunkY);
// Now retrieve the correct chunk
int[][] chunk = mapCache.get(chunkCoord); // Careful: is the chunk already loaded?
// Now retrieve the height within the chunk
int xInChunk = (x + chunkX*CHUNK_SIZE) % CHUNK_SIZE; // Made positive again!
int yInChunk = (y + chunkY*CHUNK_SIZE) % CHUNK_SIZE; // Made positive again!
// We have everything !
return chunk[xInChunk][yInChunk];
}
}
Gotcha: Your Coord class NEEDS to have a equals and hashCode methods properly overloaded!
5. It just works
This should just immediately work with your pathfinder. Enjoy!

Calling method from another class to get x and y issue

Apologies if the title is not appropriate, was having trouble what to call this.
Scenario:
I have a universe type project in java where there are different types of things you can find in a universe (stars, planets, comets etc).
This is part of my university coursework and I'm stuck on one part
I have a class called Space_Object which is a superclass and all things found in the universe inherit it. The superclass has variables such as xPosition, yPosition.
I am currently stuck on trying to get planets to orbit around stars. I am trying to get the x,y coordinates of a star so that the planet can orbit around it (there can be multiple planets and stars). Right now I am passing the star that the planet will orbit around as a field whenever making a new planet.
I created getters inside of Planet to retrieve the x,y of the Star (which works). I am stuck on how can I use that x and y to alter the starting point of the planet. This is what I added to Universe class:
public void setCoordsOfPlanet(Planet planetObj)
{
planetObj.xPosition = planetObj.getSolarSystemX();
}
Which gave me an error of:
xPosition has private access in Space_Object
I am not allowed to make any of the fields public.
Planet class:
public class Planet extends Space_Object
{
private int distanceFromStar;
private int orbitSpeed;
static Star solarSystem;
public Planet(int disFromStar, int orbSpeed, Star solSystem, int objectDiameter, Color objectColor, Universe theUniverse)
{
super(0, 0, 0, 0, objectDiameter, objectColor, theUniverse);
distanceFromStar = disFromStar;
orbitSpeed = orbSpeed;
solarSystem = solSystem;
}
public int getSolarSystemX ()
{
return solarSystem.getXPosition();
}
public int getSolarSystemY ()
{
return solarSystem.getYPosition();
}
}
Just in case, the Space_Object constructor:
public Space_Object(int xPos, int yPos, int xVel, int yVel, int objectDiameter, Color objectColor, Universe theUniverse)
{
xPosition = xPos;
yPosition = yPos;
xSpeed = xVel;
ySpeed = yVel;
color = objectColor;
diameter = objectDiameter;
universe = theUniverse;
universeHeight = universe.getUniverseHeight();
universeWidth = universe.getUniverseWidth();
lifeTime = 1000000;
}
Am I approaching this from the completely wrong angle? I been trying to change things regarding this matter for past three hours and made no progress - any help is appreciated. If you need more code let me know.
PS: All items in the universe are objects and are represented as colour circles on a canvas.
If you are asking how do I modify private fields from another class: then all you need to do is to add setter methods in your Space_Object or Planet class, for example:
public class Planet {
...
public setCoor(int x, int y) {
this.xPosition = x;
this.yPosition = y;
}
}
Now you can call this method from the Star class: planet.setCoor(x, y)
If you want this method to only be accessible from classes of the same package only, remove public.
There are multiple issues here.
Programming stuff
Model of planetary rotation
Use of 'Solar System' when it should be 'Star System' :-) The Solar System is our star system; that's because our star is "Sol"
A1. You need xposition to have a method to set it.
A2a. There are no x and y for our solar system or even a star system. If you're going to model spinning galaxies and/or expanding universe (in which case the galaxies also move in 3d space away from each other,) then the star positions (or positions of any object for that matter) are not fixed.
A2b. If you're going with immobile stars and galaxies, a star (not its system) will have an x and a y.
A2c. A planet revolves around its star in a Kepler orbit with eccentricity greater than 0 and less than 1. To calculate the path, you need axis information for the orbit in addition to the star's location. Wikipedia will have the equations.
A2d. There is no starting position of a planet unless you plan to have planets with unstable orbits. (Or comets which will have their orbits modified during every revolution by the planets they pass by). Planets with stable orbits have always followed and will forever follow the same path (not really, but...) You can place the planet at any point on the orbit and give it appropriate initial velocity (=speed+direction) and watch it go. A3. Self-explanatory
Sounds like a fun project, especially you're animating the model onscreen. In such a case, you also need to decide on your system's clock-speed; the numbers of days that will pass in real time for each second of your simulation time. Additionally, you'll need to select your refresh frequency; how often will you update the screen.

Trying to rotate a polygon using math

I have a school assignment where I'm supposed to (among other things) rotate a polygon. I can not use any premade rotate functions, so I have an array of points. The array is set up like this:
intArray[2][amount_of_points] where intArray[0] equals the points x coordinate, and intArray[1] holds the y coordinates.
//x=pivot point x coordinate, y = pivot point y coordinate.
public int[][] rotate(int[][]matrix,int x, int y, double degrees){
double s=Math.sin(degrees);
double c=Math.cos(degrees);
for (int i=0;i<matrix.length;i++){
//translate to origin
int px=matrix[0][i]-x;
int py=matrix[1][i]-y;
//rotate
double xnew = (px*c)-(py*s);
double ynew = (px*s)+(py*c);
//translate back
px=(int)((xnew+x)+0.5);
py=(int)((ynew+y)+0.5);
matrix[0][i]=px;
matrix[1][i]=py;
}
This is my code so far, and it is definitely not working out for me. I tried to trim the code as much as I could. Any help would mean a lot!
edit: I'm not getting any errors when I run the code, no exceptions etc. The only problem is that the polygon isn't rotating the way I intend it to.
I've made a test polygon:
polyArray = new int [2][3];
polyArray[0][0]=400;
polyArray[1][0]=200;
polyArray[0][1]=300;
polyArray[1][1]=500;
polyArray[0][2]=500;
polyArray[1][2]=500;
Which I draw in a JPanel, then I run this array through the rotation method like this:
polyArray=mm.rotate(polyArray, polyArray[0][0], polyArray[1][0], Math.PI);
Using the top point as pivotpoint. The whole polygon is then deformed.
Although still not very clear on question, I feel your problem is with the loop.
matrix.length is 2. So, the code never uses these :
polyArray[0][2]=500;
polyArray[1][2]=500;
If you change the condition as below, it should work :
for (int i=0;i<matrix[0].length;i++)

Vectors for a 2D/3D World in Java

I reading about Mathematics in Games and am wondering what is the best way to represent a Vector location in Java.
I know there is a Vector class but I don't think this is what I need.
There is also a Matrix class which looks like it may be what I want (a 1 dimensional matrix maybe).
In particular, if I were to create a location Vector such as:
v(x,y,z) where x,y and z are the coordinates in 3D space, what would be the best way to represent this in Java. It would be nice if I could also add, subtract and find the dot-product of Vectors.
ideas?
maybe you could create a 3DVector class
example:
class 3DVector {
int x , y, z;
public 3DVector(int x, int y, int z){
//constructor
}
public 3DVector add(3DVector anotherVector){
}
public 3DVector subtract()....
public 3DVector doProduct().....
}
There is a library for this, See :
javax.vecmath.Vector3d
There is a math library out there but a simple class with 3 floating point numbers is what everyone else uses

How to build a Tiled map in Java for a 2D game?

Not sure how to approach this problem.
Basically, I want a Pixel -> Tile representation of a 400x400 window. Each coordinate on the screen, e.g 120x300 should be part of a tile. My smallest sprite is 4 pixels, so we can say that 1 tile = 4 pixels. The player and enemy sprites are all 20 x 20, so each player/bad guy will occupy 5 tiles.
Then I want to use this Map class to:
Retrieve the x/y coordinates of a player/monster sprite by suppling the index/id of the tile.
Knowing where the boundaries are, so it doesn't move the sprite beyond 400x400, thus hiding it.
Collision detection, knowing whether a tile is vacant or not.
How can this be done? Talking specifically about the x,y->tile or tile index->x,y conversion (for drawing the sprites appropriately) here.
Firstly, split out the concept of a pixel, which is just concerned with representation, with a tile, which is an actual game object with constraints it places on the game.
I find a good way to disentangle things like this is to start out sketching out the rough API of what you want. Something like:
public class Board {
public Board (int width, int height){.. }
public boolean isOccupied(int x, int y){.. }
public void moveTo(Point from, Point to) { ..
(maybe throws an exception for outofbounds )
where all internal units of the board are in tiles, not pixels.
Then pixel information can be derived from the board independantly from the tile representation with a bit of internal multiplication-
public Point getPixelPosition(int xTilePos, int yTilePos, int pixelsPerTile)..
The tiles can be internally represented as a 2d array or a single array, in which case you'd use some kind of internal representation scheme to map your array to the board squares, thus the mod arithmetic.
Short answer: Multiplication and Modulo operations.
But if this is stumping you, I'd suggest you do a serious math refresher before trying to write a game.
Also your statement
My smallest sprite is 4 pixels, so we
can say that 1 tile = 4 pixels. The
player and enemy sprites are all 20 x
20, so each player/bad guy will occupy
5 tiles.
doesn't work out for any reasonable geometry. If by "1 tile = 4 pixels" you mean that the tiles are 2x2, then a player takes 100, not five. If you mean they are 4x4 then players take 25, which still isn't 5.
/** size of a tile in pixel (for one dimension)*/
int TILE_SIZE_IN_PIXEL = 4;
/** size of a piece in tiles (for one dimension)*/
int PIECE_SIZE_IN_TILE = 5;
public int tileToPixel(int positionInTiles){
return TILE_SIZE_IN_PIXEL * positionInTiles;
}
/** returns the tile coordinate to which the given tile coordinate belongs
Note: tileToPixel(pixelToTile(x)) only returns x if x is the upper or left edge of a tile
*/
public int pixelToTile(int positionInPixel){
return positionInPixel / TILE_SIZE_IN_PIXEL;
}
You'll probably want methods operating on two arguments (x and y at) as well.
For the ID->piece conversion and vice versa you have various approaches available. Which one to choose depends on the exact requirements (speed, size of game ...). So make sure that you are hiding the implementation details, so you can change them later on.
I'd start with a real easy solution:
public class Piece{
/** x position measured in tiles */
private int x;
/** y position measured in tiles */
private int y;
/** I don't think you need this, but you asked for it. I'd pass around Piece instances instead */
private final Long id;
public void getX(){
return x;
}
public void getY(){
return y;
}
public void getID(){
return id;
}
}
public class Board(){
private Set<Long,Piece> pieces = new HashMap<Piece>(pieces);
public Piece getPieceOnTile(int tileX, int tileY){
for(Piece piece:pieces){
if (isPieceOnTile(piece, tileX, tileY)) return piece;
}
}
private boolean isPieceOnTile(piece, tileX, tileY){
if (piece.getX() < tileX) return false;
if (piece.getX() > tileX + PIECE_SIZE_IN_TILE) return false;
if (piece.getY() < tileY) return false;
if (piece.getY() > tileY + PIECE_SIZE_IN_TILE) return false;
return true;
}
}
Hope that gets you started. All code is writen without a compiler nearby so it will include typos and of course bugs, which may be distributed under the creative commons license.
The approach of keeping the pieces in a set should work well if there are not to many pieces. It should work better than a 2D array as long as most board area does not contain a piece. The whole thing currently assumes there are no overlapping pieces. If you need those getPieceOnTile must return a Collection of pieces. A set if order does not matter, a List if it does.

Categories

Resources