Moving Objects Help - java

I want to know how is it possible,I could have an Object drawn at a certain point and move to the point that is touched on the screen. I am trying to use it for my game where when the user touches on the screen, the gun fires from the position of the player, but the player is stationary.
Thanks in advance.
P.S.
Is there a visual graphic of some sort that shows where every plot is on android.

I don't know what kind of library you're using to draw all of your things, but that basically doesn't matter since you only need to know two things in order to do this:
Without going into specifics on vector geometry:
1. You need to calculate the direction (x and y component) that the projectile moves in depending on your mouses position. You get this direction by simply subtracting the position of the mouse from the position of the player:
//x component of direction
float direction_x = mousePosition.x - playerPosition.x;
//y component of direction
float direction_y = mousePosition.y - playerPosition.y;
In order to just get a direction instead of adding a velocity component to this vector, you need to normalize it (so it has a length of 1):
float length =(float) Math.sqrt(direction_x*direction_x + direction_y*direction_y);
direction_x /= length;
direction_y /= length;
You then need to update the projectiles position by adding the direction_x and direction_y components to it, multiplied by the speed that you want the projectile to have (This process is called linear interpolation, by the way):
projectile_x += direction_x*speed;
projectile_y += direction_y*speed;
If you have some way of measuring the time between two frames, the speed variable should depend on the elapsed time between those frames, in order to create smooth movements on different platforms.

Related

How to properly combine two camera view matrices?

Basically, I have a 3D hexagonal tile map (think something like a simplified Civ 5 map). It is optimized to use a single large mesh to reduce draw calls and easily allow for some cool Civ 5 features (terrain continuity and uv texture bleeding).
I want to support wraparound maps in my game, and so was brainstorming ideas on how to best do this.
For example, if the main camera is approaching the far east of the map, then I can simply perform the translation to the far west by doing:
if(camera.x >= MAP_WIDTH)
camera.translate(0, 0, y);
However, by doing this, there will be a brief timespan in which the player will see the "end" of the board before the translation. I want to eliminate this.
The first idea I had to solve this problem was to basically just modify the above code as follows:
if((camera.x + camera.viewportWidth >= MAP_WIDTH)
camera.translate(0, 0, y);
However, this has the side effect of a "jump" during the translation that feels unnatural.
My final solution, and the subject of the question:
I have three cameras, my main camera, one to the far east, and one to the far west. I basically want to "combine" the matrices of these cameras to render the map outside of its actual bounds.
Basically, if the camera is a certain distance from the world bounds, I want to draw the scene from the other side of the world in the following location. So, for example, this is the pseudo code of what I want to do:
int MAP_WIDTH = 25;
float viewportSize = 10f;
float mainCamX = 24f;
float mainCamY = 15f;
Matrix4 cbnd = camera.combined;
if(camX >= MAP_WIDTH)
camX = 0;
else if(camX < 0)
camX = MAP_WIDTH - camX;
if(camX + viewportSize >= MAP_WIDTH)
cbnd = combineMatrices(mainCam.combined, westCam.combined);
modelBatch.setProjectionMatrix(cbnd);
modelBatch.begin();
//Draw map model
//Draw unit models.
modelBatch.end();
modelBatch.setProjectionMatrix(mainCam.combined);
But I am unsure of how to appropriately combine matrices, and am new to the concept of matrices in general.
Can somebody give me a hand in combining these matrices?
Sounds too complicated. Here is my idea:
I.e. you can display 10x10 fields on screen
you have map 100x100 fields
just increase your map to 110x110 and in that extra space repeat your first (zero-est rows and columns)
that way you can scroll smoothly and when camera reaches i.e. most right position you have on map just return it to 0 X position. Same goes for vertical movement.
So, idea is to have double most left part of map in width of screen width and most top part of map in size of screen height at rigth/bottom of the map respectively.

How to create a counter that updates via a mouse drag?

Lets say I have a circle, and if the user drags his mouse clockwise along the path of the circle the counter increases, and if he drags the mouse counter-clockwise it decreases. What is the best way to implement this in Java? I imagine trig will be needed so the program knows when the user is dragging clockwise or counter-clockwise, right? Not looking for code examples, just help with theory so I can begin with the right approach.
As you probably have access to the circle, get its center point coordinates.
Then get the coordinates of the mouse. After that you compute the angle between the vector and the x-axis.
You do so by first setting the circle point as the center of the imaginary coordinate system and then shifting the mouse coordinates to this system. After that you apply atan2 on the new mouse coordinates. The result is the desired angle.
Point center = ...;
Point mouse = ...;
Point shiftedMouse = new Point(mouse.x - center.x, mouse.y - center.y);
double angle = Math.atan2(shiftedMouse.y, shiftedMouse.x);
At this point you probably need to convert the result of angle to degrees or something like that, if you like. You may take a look at Wikipedia#atan2 for this.
Of course you can also leave it in the format (-pi, pi] and work with that, if you know what it means.
Now you track how this angle changes. If it increases, then the mouse is moving counter-clockwise; if it decreases, then clockwise and so on (or maybe the other way around, just try it). Take care of the bound where after 359° 0° and then 1° comes.

Pacman collision detection with varying character speeds?

I am programming a 2D, grid-based Pacman game. All the tiles are 8x8 in size. In-game, the map tiles are treated as 16x16, and the characters (Pacman and the ghosts) are treated as 32x32. In actuality, they are all pulled from a spritesheet of 8x8 tiles. I store positions as the center point of each character. Since the character tiles are bigger than the map tiles, the map is built in a way that requires the characters being able to "overlap" onto blocked tiles.
To deal with this set of problems, I created an invisible Rectangle and attached it to the character's position. Where the position is an (x,y) point, the Rectangle is a box surrounding that point. This rectangle is essentially 16x16 in-game, and is in the center of the character, which allows for the overlap necessary.
This works fine if you're working with 8px as the global movement speed, but I'd like to treat 8px as "100% speed" and have complete control over character speed with a double that is in the range [0,1). The positions are stored as double points, so on that level, this is fine. I read the positions back as integers, though, since I'm working with pixels.
So the question I ask is essentially "if this moves X amount of pixels to direction Y now, will my collision box be touching a blocked tile? But if you're moving 5px at a time, this eventually causes a very obvious issue. Say you're at x = 0, moving right. The tiles are 16x16 in-game, as stated before, and you have two of these open before the third, which is blocked. So you move, x = 5, x = 10, x = 15, x = 20, we just got to the 2nd tile, x = 25, x = 30, x = 35 now we're in the 3rd tile... but wait. We can't go there, because X = 35 collides. And unfortunately, we needed to turn and start moving down, but we can't, because now our Y-axis isn't aligned properly with the grid. Our X position needs to be 32, but can't.
My question for everyone here is, what are my options? What are some ideas or insights you have? I have a feeling I'm making it more difficult than I need to.
sounds like you have...
Why not give your "pac-man" sprite a velocity vector? The vector will describe not only the speed at which "pac-man" is traveling but in what direction, meaning you can see ahead.
"pac-man" should be calculating and ultimately making a decision based upon the following conversation..."hey, moving at this speed and in this direction..in so many seconds I'm going to hit a wall, when does that happen?". The seconds don't even have to be seconds...they could be "squares".
You would need a function which takes in the initial movement vector (direction and speed) which returns a coordinate of an X,Y point where "pac-man" must stop, where he cannot go further and must change direction (the center of a tile adjacent to a wall). Each time "pac-man" changes direction, run this calculation again...you do not need to keep checking if the next square is passable. If his direction hasn't changed and his speed is constant..you only need calculate once and let the coordinate system do the rest.
With this approach, square size and velocity is irrelevant...until "pac-man" hits or within his next movement exceeds the stopping point, continue to move along the vector.

Making a rectangle go around in a circle - Java/Swing

My maths isn't that good so I'm having a bit of trouble in one of my applications that I'm trying to do where I want a rectangle to represent a vehicle and I want that vehicle/rectangle to "drive" around in a circle. Imagine a roundabout with only 1 vehicle in it, just circling around forever.
If I can get some help how to do that then I'll be able to build on the example and most importantly learn.
If someone could write up a simple example for me I'd be grateful. No background no images, just a rectangle "driving" around in a circle. I'm using java and Swing.
Sorry, I am not sure if could understand clear you exactly need. If you need to draw rectangle which is moving around inside of circle, you can use sin/cos functions.
Something like that:
double r = 50.0; // radius (it might radius of your circle, but consider dimensions of rectangle to make sure you are drawing inside of circle, e.g. circleRadius - rectangeDimesion / 2.0)
for (int f = 0; f < 360; f++) {
double x = Math.sin(Math.toRadians((double)f)) * r;
double y = Math.cos(Math.toRadians((double)f)) * r;
// draw rectangle on [x, y] coordinates
}
If you know the radius of the round about, all the you would need would be a trigonometric function and the angle which the vehicle makes to the round about. You could take a look at this simple introduction which should get you started in the right direction.
On another hand, another approach would be to use a Transformation Matrix where you start with a matrix containing two points (your X and Y co-ordinates) and you transform them to become the new co-ordinates.
You can then rotate the rectangle to mimic a vehicle turning.
If you have a limited background in Mathematics, the first option might be easier for you to grasp.
This is more an extended comment than an answer.
I would divide the problem up into several easier problems, and work on each of them separately:
Draw your rectangle with a specified center location and long axis orientation.
Determine the center point and long axis orientation for an object orbiting around the origin. Note that to get make the long axis a tangent it needs to be perpendicular to the radius through the center.
Translate the whole system so that it orbits the desired point, rather than the origin.

How to coordinate graphical and logical position in a 2D tile based game using an array?

I'm programming a 2D tile based game in Java like Bomberman (my first game).
I use a 2D array to represent the map where I keep track of walls, walkable spaces, etc. By now I was able to make the player move smoothly swaping sprites depending on the direction key he presses (but not interacting with the background/map, it can walk randomly and get out of the screen).
My problem comes when I want to keep track of the player's position in the array. Logically the character always belongs to only one tile but graphically it can be between two tiles. How can I solve this issue?
I already tried this:
currentTileArrayX = x / tileWidth;
currentTileArrayY = y / tileHeight;
Where x and y are the top-left coordinates of the sprite.
But everything became very buggy because the player's sprites aren't the same size as the tiles.
I had another option in mind that would solve the previous problem: When the player presses a direciton key, move the character to the next tile like an animation. This wouldn't let the player stop in the middle of two tiles... But what if he interrupts it with another key press? How can I stop user's action while the animation is executing? I think this is the easiest solution but I don't know how to implement it.
I already tried to find the solution in other questions but I had no luck. I hope you can help me.
Thanks a lot.
Aaaaaaaaaaaaaaah! Encountering the 'discrete space problem' :) Your logic map is discrete but your UI movements are in the continuous space. I don't the user can actually be in both tiles "at the same time" - visually yes, but never 'internally'. Now you are getting the position of the player and that can be "anywhere" within the tile or "on the boundary" of 2 tiles so to speak...
You have two solutions to this problem, IMO:
Use simple rounding: If the player position is < tile-boundary just keep him on the previous tile. If Greater on the next. Now the problem of boundary - you can use a heuristic, since you shouldn't trust the accuracy of the floating point comparisons (i.e, comparing to 0 is not a good thing to do). So you can try something like this if(currentPosition - boundary <= 0.000000001) then assume it's the next tile else stay on the same one.
Well #Jay beat me to it. So the second one is to actually have a
movement speed defined and move the character that many steps per
'click'/'button press' - but you say you have the problem of key
pressed in "between". I'm guessing if you code is designed like this
then it shouldn't be a problem:
update()
{
calculate(); //update all datastructures/calculations
draw(); //update the visual representation based on calculations
}
update() is a.k.a, gameLoop. I think this should solve your problem...
I'd try to keep the logic part (tile the player belongs to) and the visualization part (animation between tiles) as seperate as possible. My approach would be to have a logical location (tile the player is set on) and a movement speed (which essentially means an amount of time the player isn't allowed to move on to the next tile after moving to a tile). Then the animation from one tile to another would mean that your sprite is always moving towards the screen coordinates of your tile - the time this takes could easily be determined by the movement speed (one full tile movement should take as long as the player has to rest on the current tile).
The only special case would be this "turning around", where you would allow the player to return to the tile he came from at any time, taking only (timeToRecoverOnTile - (timeToRecoverOnTile - timeSinceMovementStarted)).
I once did basically the same thing in AS3, but the concept transfers to Java. I decided to create two main values to help keep track of movement, a Point containing the player's x/y value (by tile), and a direction Point for the movement's direction. Here's some pseudo-code:
if(direction.x == 0 && direction.x == 0) {
if (up) direction.y = -1;
else if (down) direction.y = 1;
else if (left) direction.x = -1;
else if (right) direction.x = 1;
} else {
player.x += direction.x;
player.y += direction.y;
distance--;
if(distance == 0) {
direction.x = direction.y = 0;
distance = tileWidth;
}
}
Obviously, you'd have to tweak that to fit your needs, but that's the basics. Also, tileWidth can be replaced with an integer literal that simply is equal to the width of a single tile.

Categories

Resources