Gaming, collision on view - android

I am designing an archer game. When the arrow hits the target it stops moving. What I am trying to accomplish is to define a formula to predict/get location where the target and the arrow meet on the view.
The problem arises when the arrow got a speed varying on initial velocity and the arrow also have angles. Plus, the images on screen are placed by x - bitmapt.getWidth/2 (same for height, h/2..)
If an arrow moves too fast then I need to calculate an error so the arrow does not miss the target even though they are supposed to be on same x and y as we have that, the arrow moves as X + speed pixels. So I came to something like this!
if(arrow[i].getX() + v0x[i] / 2 >= target.getTarget().getX() && arrow[i].getX() <= target.getTarget().getX() + v0x[i] / 2)
I use the velocity of x/2 to specify the error margin.
arrowX + velocity/2 >= collision point >= targetX + velocity/2
However, it does not work.

This is a pure mathematical problem, and there are much literature when it comes to collision detection. I propose that you use a library. For 2D I recommend JBox2D. It is a physics engine (used for example in Angry Birds). You get collision detection and much much more :)

Related

Warp Image area on touch of a point area?

I need a basic idea for how can i warp image on touch of a particular area. Image filters apply warp on whole image but i want to warp single point, like if i want to warp eye of a person then i will touch on that point. So I need a basic idea about this work.
I have tried this one but its also applies filters on whole image.
https://github.com/Jtfinlay/PhotoWarp
App:
https://play.google.com/store/apps/details?id=hu.tonuzaba.android&hl=en
A warp is not just at a "single point" but over some area that you deform in a smooth way.
To achieve this, you need a geometric transform of the coordinates that works in some neighborhood of the touched point. One way to do this is by applying a square grid on the image and moving the grid nodes around the touched points with some law of yours (for instance, apply a displacement vector to all nodes, with a decaying factor such that far away nodes don't move).
Then you need a resampling function that computes the new coordinates of every pixel and copies the color of the source pixel.
For good results, you must actually work in reverse: scan the destination image and for every pixel retrieve the source coordinates and source pixels. Apply bilinear or bicubic resampling to avoid aliasing.
For ease of implementation, the gridding idea should be adapted as well: rather than deforming the destination grid, keep it unchanged and apply the inverse deformation to the source grid.
Last thing: in the grid approach, see the displacements of the grid nodes as two scalar functions DX(i, j) and DY(i, j) that you can handle separately. From the knowledge of the displacements at the nodes, you can estimate the displacement of any pixel by interpolation (bicubic would be appropriate here).
you can use canvas to detect that portion and stop action on that portion in ontouchlistener
code sample
Bitmap pricetagBmp = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.ic_tag_circle_24dp);
// canvas.drawBitmap(pricetagBmp,left + (right - left) / 2, top + (bottom - top) / 2 - (bounds.height() / 2),circlePaint);
float imageStartX = (left + ((right-left)/2)) - (pricetagBmp.getWidth()/2);
float imageStartY = (top + ((bottom - top) / 2)) - (pricetagBmp.getHeight()/2);
canvas.drawBitmap(pricetagBmp, imageStartX, imageStartY,circlePaint);
and in ontouchlistener if that points detected you can perform no action
Note: you can replace drawBitmap with drawRect or something else with invisible color

Generating Objects outside of Screen and then Moving them to Center?

Is it possible to generate a series of objects outside of the screen, and then making those objects move inwards? I am creating a live-wall paper with circles that start outside of the screen, and move inwards and bounce off the walls. I have created an illustration to better describe what i mean:
The 2 Issues im facing are:
Generating Objects outside of screen
Making them move inward and then bounce off the edges
How can i achieve this?
One solution to this problem would be to create a class which would contain following attributes:
X and Y coordinated (could be Point)
speedX
speedY
Then you could create objects with coordinates:
(X < 0) or (X > screenWidth)
and/or
(Y < 0) or (Y > screenHeight)
and give them appropriate speed (so they move towards the screen boundaries).
In each step you would:
update each object's coordinates, moving it in appropriate direction corresponding to its current speed
redraw all objects on your canvas
The offset of object's coordinates depends on time step between each two redraws. It's up to you how you want to evaluate it.
Until an object reaches screen boundaries it will be drawn outside the screen and not visible.
To draw the objects on canvas you could extend View class (or SurfaceView - difference between these two is discussed here) and override onDraw() method. You can follow this tutorial or find another one by yourself (there are lots of it).
If an object reaches the screen boundary from its inside (i.e. when its X is in range [0, screenWidth] and its Y is in range [0, screenHeight]) you can negate its speed (in X or Y direction, depending on which boundary has been reached) so it would go in the other direction (like in an elastic collision with a wall).
You can adjust speedX and speedY minimum and maximum values to see which give the most satisfying results.

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)

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