How do I recursively draw a hex map in opengl? - android

I'm new to GL and wanted to create a tiled map as a self tuorial. I want to create a small (maybe 7 hexes wide / tall) hex map. My first thought was to just create a method to draw one hex and then just translate the appropriate offset and place the new hex. But this doesn't seem effcient. Any Idea's? Alos as a side question, how do I determine if a MotionEvent is with in the are of a given hex?

Extensive hex grid information.

To determine if a MotionEvent is within a certain hex you have to convert the coords passed in via the motion event to your OpenGL World coords. Its just like a unit conversion, you know the screen goes from 0 - WIDTH and your GL world lets say goes from -1 to 1.
(xCoord / (Width - 0)) * (1 - (-1)) = xCoordWorld
will give you the xCoord from 0 to 2, then subtract 1 to get it in -1 to 1.
As far as the hexes go I've always used 'art' hexes. Draw the hex out in paint then render a bunch of squares with that piece of art on them, fast and easy to swap a hex out for another hex.

Related

Android libGDX moving object and detect

I just started experimenting libgdx and understanding... I looked sample projects... My problem :
The 1 and 6 originial ball number. And other balls, the ball's(1 and 6) will go randomly other places. (speed 1). ex . If a i am torch on the any ball, its speed up to 3...
The GameObjects should be in while loop. Ball images sometimes (randomly), the balls should be retun own 360 degrees. And get picture on TectureRegion.
Is there a similar example ? or
How can I do this ?
(Sorry for bad english)
Thanks...
As much as i understood you want your ball objects to move arround until you quit the game. Also you want to speed them up on touch right? Also you want to texture them and maybe they should detect collision with the screen borders and other balls to?
Libgdx has a main loop. This loop calls render(delta) every renderloop. The delta depends on the time ellapsed since last call of render. So on fast devices this delta is smaller then on slow devices (most times). This time is given in seconds. To move your objects you can add a value to their position in every render loop. In your case you want to add 1 (hopefully not pixel, as it then would seem slower on big screens):
for(BallObject ball : ballObjects) {
ball.setPositionX(ball.getPositionX() + ball.getSpeed() * delta * direction.x);
ball.setPositionY(ball.getPositionY() + ball.getSpeed() * delta * direction.y);
}
In this case a BallObject has a positionX and positionY describing his current position, a direction.x and direction.y, describing his movement in x and y direction (for 45° it would be direction.x=0.5 and direction.y=0.5), as well as a speed describing movement per second. This speed will be set to 3 on touch.
To speed the ball up on touch, you first need to implement InputProcessor in the class, which manages the movement of all ballobjects. Next you have to set it as the InputProcessor of the game: Gdx.input.setInputProcessor(this);. The InputProcessor has a method touchDown(int x, int y) or something like that. The x and y value are giving the coordinates in pixels, on the screen.
If you are using a camera or viewport in the new Libgdx version (you should do that) you have to use camera.unproject(x,y) or the viewport version of that (idk the exact method name). This method gives you the touchposition in your world coordinate system. Then you can simply check which ball is on this touchpos and set its speed to 3.
To texture the ball you have to use SpriteBatch for drawing. Look at the different draw() methods in the API and use the one which fits best for you. Just load a Texture, which should be a ".png" with a circle texture and the rest of it should be transparent (alpha = 0). With blending enabled (default) it will then only render the ball, even if it is actually a rectangle shaped Texture.
I hope it helps

Best approach to make a background scrolling game?

i want to do a 2D game with backgrounds and sprites (views) moving on the screen.
I want to make a game with a scrolling ground. I mean the user must see a horizon in the top part of the screen filling the 30% of the screen size. The ground must be scrolling and must be the 70% of the screen size. For example, if i put a car on the ground, the car must be driving into a scrolling road and the sky (horizon) must be seen on the screen, in the top of the road, filling the 30% of the screen.
I am searching in google about scrolling games but i can't find the way to achieve this kind of scrolling ground game with horizon.
Any ideas and approaches will be grated, i'm just making a research about how to do this.
Thanks
This kind of effect can be done in various ways, here is one very basic example I can come up with.
First create a background image for your horizon - a blue sky with a sun would be good. Now create some detail images for the background, such as clouds and birds. These can move accross the background image from left to right (and/or vice-versa). In your rendering code you would render the "background" image first, and then the "detail" images. Make sure that your background image covers around 35% of the screen, so that when you render the 70% ground layer there is some overlap - preventing a hole where the two layers meet.
Next create a textured image for the ground. For this I would use a static image that has the correct type of texture for what you are trying to represent (such as dirt). It may also be good to add some basic detail to the top of this image (such as mountains, trees, etc).
This should be rendered after the background layer.
Once you have this layout in place, the next step would be to simulate the depth of your world. For this you would need to create objects (2D images) that would be placed in your "world". Some examples would be trees, rocks, houses, etc.
To define your world you would need to store 2 coordinates for each object - a position on the x-axis as well as a depth value on the z-axis (you could also use a y-axis component to include height, but I will omit that for this example).
You will also need to track your player's position on the same x and z axis. These values will change in realtime as the player moves into the screen - z will change based on speed, and x will change based on steering (for example).
Also define a view distance - the number of units away from the player at which objects will be visible.
Now once you have your world set up this way, the rendering is what will give the illusion of moving into the screen. First render your player object at the bottom of the ground layer. Next, for each world object, calculate it's distance to the player - if it's distance is within the view distance you defined then it should be rendered, otherwise it can be ignored.
Once you find an object that should be rendered, you need to scale it based on it's distance from the player. The formula for this scaling would be something like:
distance_from_player_z = object.z - player.z
scale = ( view_distance - distance_from_player_z ) / view_distance
This will result in a float value between 0.0 and 1.0, which can be used to scale your object's size. Using this, the larger the distance from the player, the smaller the object becomes.
Next you need to calculate the position on the x-axis and y-axis to render your object. This can be achieved with the simple 3D projection formulas:
distance_from_player_x = object.x - player.x
x_render = player.x + ( distance_from_player_x / distance_from_player_z )
y_render = ( distance_from_player_z / view_distance ) * ( height_of_background_img );
This calculates the distance of the object relative to the player on the x-axis only. It then takes this value and "projects" it, based on the distance it is away from the player on the z-axis. The result is that the farther away the object on the z-axis, the closer it is to the player on the x-axis. The y-axis part uses the distance away from the player to place the object "higher" on the background image.
So with all this information, here is a (very basic) example in code (for a single object):
// define the render size of background (resolution specific)
public final static float RENDER_SIZE_Y = 720.0f * 0.7f; // 70% of 720p
// define your view distance (in world units)
public final static float VIEW_DISTANCE = 10.0f;
// calculate the distance between the object and the player (x + z axis)
float distanceX = object.x - player.x;
float distanceZ = object.z - player.z;
// check if object is visible - i.e. within view distance and in front of player
if ( distanceZ > 0 && distanceZ <= VIEW_DISTANCE ) {
// object is in view, render it
float scale = ( VIEW_DISTANCE - distanceZ ) / VIEW_DISTANCE;
float renderSize = ( object.size * scale );
// calculate the projected x,y values to render at
float renderX = player.x + ( distanceX / distanceZ );
float renderY = ( distanceZ / VIEW_DISTANCE ) * RENDER_SIZE_Y;
// now render the object scaled to "renderSize" at (renderX, renderY)
}
Note that if distance is smaller than or equal to zero, it means that the object is behind the player, and also not visible. This is important as distanceZ==0 will cause an error, so be sure to exclude it. You may also need to tweak the renderX value, depending on resolution, but I will leave that up to you.
While this is not at all a complete implementation, it should get you going in the right direction.
I hope this makes sense to you, and if not, feel free to ask :)
Well, you can use libgdx (http://libgdx.badlogicgames.com/).
The superjumper example will put you in the right way :) (https://github.com/libgdx/libgdx/tree/master/demos/superjumper)

Drawing on the android screen with a coordinate system

My question is probably going to be initially very confusing to read, so just bear with me. I'll start it off with a little preface for context:
Preface:
I have an app that will be using an array for path-finding from a map.
^That is very vague: There will be an array of characters, representing walls, stairs, etc., and there will be a function that finds the best path.
I want to display the path on the android screen.
There will be characters that are generated by the array function that represent the generated path (probably "x" or something).
Okay, to make it more clear: There will be a "path" of 'x's in an array. These 'x's represent the path that is going to show up on the Android screen.
My actual question:
How do I translate an 'x' in the array to displaying a line on the screen? I had the idea to use a for loop/if statement that checks if there is an 'x' and if there is, then to display a little red dot/line in a second array that represents the actual screen.
I was trying to find this, but it's such an awkward thing to type into google, so I finished my research with nothing.
Is there some sort of built-in android function that lets you assign different colours to different coordinates?
This is kind of what I want to appear on the screen. If this were the app, the blue would be represented by 'x's in the first array.
there could be several ways to achieve this effect of having a coordinate system mapping to a matrix that describes a path.
Depending on the size of the array and the frequency of update calls (it sounds like the path finding runs once with a single render after), it probably wouldn't be too expensive to just loop through. What I personally would do is start to look at how to draw on a canvas, get the screen size, and adjust the bounds accordingly.
Get screen dimensions in pixels - How to get screen dimensions
http://danielnadeau.blogspot.com/2012/01/android-canvas-beginners-tutorial.html - A nice tutorial on canvases
Once you can draw to a scaled canvas, it is simply a matter of running a loop that looks something like:
float scale_x = screen_width/columns;
float scale_y = screen_height/rows; //pixels per grid square
for( int x = 0; x < columns; x++)
for( int y = 0; y < rows; y++)
if( data[x][y] == 'x') drawRect(x*scale_x, y*scale_y, scale_x,scale_y) //if something found, draw a colored square

opengl 2d image grid in android

I need to draw a gridded image using opengl. I've read that images created using grids allows to do various effects on images, like the famous wave effect, or a ripple effect from this link:
http://www.soulstorm-creations.com/index.php?option=com_content&view=article&id=111:opengl-making-a-2d-grid-image&catid=18:programming-articles&Itemid=39
I've also gone through lesson 6 android port from NEHE Tutorials:
http://insanitydesign.com/wp/projects/nehe-android-ports/
I can convert it from cube to rectangle, but I need help in understanding
1) why we are using vertex coordinates in terms of 0 and 1? Why have they not used coordinates according to image width and height?
2) How can we divide the texture region in small grids as explained in tutorial above? If some one can guide on 1), I guess I can work on point 2).
Any help would be really appreciated.
The vertex coordinates are from 0 to 1 so that you can use vertex data with many different textures without worrying about the dimensions of the image.
That said, for pixel perfect operations you often have to often the texture coordinates by a fraction the image's pixel width (say 0.5f * (float) image->width()) and height in order to make sure OpenGl (or d3D) samples from the correct place.
As for dividing the grid, straight forward simple linear interpolation. If you have a grid going from pixel coordinates 0 to 100 and you want 10 steps in your grid, you start at 0 and increment in steps of 10 pixels :
vertex_xi = (start_x + ((end_x - start_x) / 10) * i));
vertex_yi = (start_y + ((end_y - start_y) / 10) * i));
similarly,, for texture coordinates, you'd do the same thing only you usually name them like this:
vertex_ui = (start_u + ((end_u - start_u) / 10) * i));
vertex_vi = (start_v + ((end_v - start_v) / 10) * i));
where 'start_u' and 'start_v' are '1.0f +/- offset and end 'end_u' and 'end_v' are '1.0f +/- offset'. Put those in your vertex array and you should be good to go.
HTH.

Calculate angle of moving ball after collision with angled or sloped wall that is a 2D line segment

If you have a "ball" inside a 2D polygon, made up of say, 4 line segments that act as bounding walls, how do you calculate the angle of the ball after the collision with the irregularly sloped wall?
I know how to make the ball bounce if the wall is horizontal, vertical, or at a 45 degree angle. I also have my code setup to detect a collision with the wall.
I've read about dot products and normals, but I cannot figure out how to implement these in Java / Android. I'm completely stumped and feel like I've looked up everything 10 pages deep in Google 10 times now. I'm burned out trying to figure this out, I hope someone can help.
Apologies in advance: I don't know the correct Android types. I'm assuming you have a vector type with properties 'x' and 'y'.
If the wall were horizontal and the current velocity were 'vector' then it'd be as easy as:
vector.y = -vector.y;
And you'd leave the x component alone. So you need to do something analogous, but more general.
You do that by substituting the idea of the line normal (a vector perpendicular to the line) for hard coding for the y axis (which is perpendicular to the horizontal).
Since the normal is orthogonal to the line, it can be found by rotating the line by 90 degrees. In 2d, the vector (a, b) can be rotated by 90 degrees by converting it to (-b, a). Hence if you have a line from (x1, y1) to (x2, y2) then you can get the normal with:
vectorAlongLine.x = x2 - x1;
vectorAlongLine.y = y2 - y1;
normal.x = -vectorAlongLine.y;
normal.y = vectorAlongLine.x;
You don't actually care how long the original line was (and it'll affect computations later when you don't want it to), so you want to make the normal be of length 1 irrespective of its current length. You can do that by dividing it by its current length. So, e.g.
lengthOfNormal = Math.sqrt(normal.x*normal.x + normal.y*normal.y);
normal.x /= lengthOfNormal;
normal.y /= lengthOfNormal;
Using the Pythagorean theorem there to get the length.
With the horizontal line, flipping on the y axis was the same as (i) working out what the extent of the vector extends along the y axis; and (ii) subtracting that amount twice — once to get the velocity to be 0 in that direction, again to make it the negative version of the original. That is, it's the same as:
distanceAlongNormal = vector.y;
vector.y -= 2.0 * distanceAlongNormal;
The dot product is used in the general case is to work how far the vector extends along the normal. So it does the same as taking vector.y does for the horizontal line. This is where you possibly have to take a bit of a leap of faith. It's a property of the dot product and you can persuade yourself by inspecting a right-angled triangle. But for now, if you had a horizontal line, you'd have ended up with the normal (0, 1). Since the dot product would be:
vector.x * normal.x + vector.y * normal.y
You'd compute:
distanceAlongNormal = vector.x * 0.0 + vector.y * 1.0;
Which is obviously the same thing as just taking the y component.
Having worked out the distance along the normal, you actually want to then subtract that amount times the normal times two. The only additional step here is multiplying by the normal to get a 2d quantity to subtract. That's because you're looking to subtract in the order of the normal. So complete code, based on a normal computed earlier, is:
distanceAlongNormal = vector.x * normal.x + vector.y * normal.y;
vector.x -= 2.0 * distanceAlongNormal * normal.x;
vector.y -= 2.0 * distanceAlongNormal * normal.y;
If you hadn't made normal of length 1, then you'd need to divide by the length here, since the dot product would scale the distanceAlongNormal value by that amount.
This might come in handy for you
http://www.tonypa.pri.ee/vectors/tut07.html

Categories

Resources