I am creating a simulation of a crowd using Java Swing and Java Graphics2D. I have a certain number of pedestrians that must reach some waypoints and I am having troubles with their motion.
The movement of each pedestrian now is very simple, it is something like this:
if (goalPosition.x > pedestrian.position.x) {
pedestrian.position.x++;
}
else
pedestrian.position.x--;
if (goalPosition.y > pedestrian.position.y) {
pedestrian.position.y++;
}
else
pedestrian.position.y--;
I just increase/decrease by 1 the position of each pedestrian according to the position of the goal to reach.
The problem is that i need to make them walk towards the goal in a straight line, I tried to compute angles and use trigonometry, but the problem with that approach is that I can't update the position of a pedestrian using a double value, because later each pedestrian is drawn using:
g2D.fillOval(pedestrian.position.x, pedestrian.position.y, ENTITY_SIZE, ENTITY_SIZE);
That accepts only integer positions.
Any idea of how I can update my code? Thanks
Related
I'm trying to build a logic function for my map building application that will tell me if there is an available path from one swing object to another.
Specifically I want to identify all the possible paths from one Jabel to another Jlabel.
Empty space is denoted by a white image, a wall is denoted as a blue image, player start is orange, and player finish is green.
So what I think I want to do is check each available path from the starting point. If the path ends at the goal return true, if it ends at a wall then make that the new starting path. My current Idea is to create a 2d array that populates with ints 0. When a the user changes a tile to something other than white, a corresponding spot in the array will change to 1 2 or 3 depending on what tile they placed. Then when they try to save the map the algorithm would use that 2d array to represent the map and check adjacent and linear paths.
Am I on the right track with this or is it more complicated?
I feel like this could turn out to be very slow(like n^2 or worse) if it's a complicated map because the paths can branch out. I'm thinking about using a sort of Dijkestras method for solving this, but I also don't know how exactly I would do that in swing.
There are some movement restrictions in the game as well.
You can't change directions unless you are stopped.
You can't stop unless you hit a wall or the edge of the map.
This eliminates a few options to sift through, as the number of paths become alot more limited.
Yes I think you are on the right path.. You can use something like this for collision:
In which you made a object, class Coordinate
constructor(){
block = new Coordinate[length];
path = new Coordinate[length];
for (int i=0;i<number_of_blocks;i++){
if (block[i].x==path[length_of_path].x && block[i].y==path[length_of_path].y){
//now you have a collision so go back
}
or
for (int i=0;i<number_of_blocks;i++){
if (block[i].x==path[length_of_path].x+1 && block[i].y==path[length_of_path].y){
//now you know you have a block on the right side
}
In which you have to make a object for, class Coordinate for example, to help store the coordinates.
class Coordinate {
int x,y;
Coordinate() {
x=0;
y=0;
}
Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
This way you can easily check if there is a collision or not and if you're out of bounds. Then you change direction adding a new coordinate to you string with the new coordinates and so on. I think this is easier then using 2d Arrays.
If you're array is out of options you go back till there is another direction possible and go that way. (You only have to save seperatly what your previous coordinates were and overwrite them while you go back).
GL
I am coding a game using LibGdx and I have an array with all of my wall objects that the player can collide with. For those who don't use LibGdx, I am talking about LibGdx's Array class which provides the same functionality as an ArrayList but it's built with memory efficiency in mind. When I check for collision, I am having to go through every wall in the array and check for collision like this:
for(Wall w : walls) {
if(w.bounds().contains(player.bounds()) {
// handle collision
}
}
I realized this was inefficient because I am going through every wall even if that wall is off the current view of the map. Obviously, if I am checking for collision with walls currently in the camera's viewport (this means they are currently visible by the player) then there is no point in going through the whole array because the player can't collide with them until they come into view. I was thinking of making my game a bit more efficient by only checking for collision with walls close to the player. In my game, I have all of the walls snapped onto a grid with cells 32x32 px. I really don't know how I could create more efficient searching for collision. Could I use like a map of some sort which uses a vector2 position for its key and then look up the player's position and look through walls within a certain range from the player's position in the map? I am just really lost on how to have code that won't go through all 100+ walls in my game when there are only 10 current possible walls that the player could touch because of where it currently is. Does this make any sense? Could someone explain a good way to do something like this? Thanks so much.
There are lots of collision alghoritms out there, you will need to find one that suits your need.
One solution I can think of on the top of my head is:
Keep your wall list sorted on their coordinates. If you create a new wall, use insertion sort to resort your array. When you want to check for collisions, take the objects coordinates (in this case probably the player that is running) and do a binary search to find the closest wall to the player. Then calculate if the player and this wall collides. If the closest wall isn't causing a collision, you can be pretty confident that no other wall is as well.
Each wall is on one or more of these 32x32px grids. Let the coordinates of a grid be x and y. If a grid contains a wall, enter this into a
HashMap<CoordPair,Set<Wall>> xy2wall
To investigate where a location is in contact with a nearby wall, use the coordinates of the location to determine a small set of grid coordinates, fetch the set or sets of Walls mapped by these CoordPairs. I guess the Player.bounds() can provide a suitable set of coordinates.
If the 32x32 grid results in too many entries, you can always use a coarser grid.
I once came into the same realization that you have while developing a top down rpg.
There are more walls than you can imagine in a top down rpg.
Here is how I solved it:
First: Segment the map into zones ie.) draw your map on paper or something and cut it up into parts.
Second: Record the pixel boundaries for each segmented section of the map.
Third: Check where your players location is with respect to the boundaries.
Finally: Only check the walls within those boundaries.
In a realm of infinite walls this is not any more efficient (speaking about Big O) but for all practical purposes this is effective in cutting down on lookup times
if (boundary1.contains(player1)) {
for(Wall w : Boundary1Walls) {
if(w.bounds().contains(player.bounds()) {
// handle collision
}
}
}
else if (boundary2.contains(player1)) {
for (Wall w : Boundary2Walls) {
if(w.bounds().contains(player.bounds()) {
// handle collision
}
}
}
....
Continue in this fashion
Take note... I did it like this before going to college for software development, so I did not make use of data structures such as BST which could be used to store walls with respect to their coordinates. Making your lookup time extremely fast.
I am currently working on a game in LibGDX. You may have seen another post. I have solved that problem, but now, I am facing the fact that I can't seem to move my player towards (it always moves up instead of pointing towards its front). I have tried everything, from using Box2D to answers I found online that suggested to use trig functions. Has anyone managed to do this before?
The movement of objects is usualy done by setting their x (left and right) and y (up and down) coordinates.
To know how to manipulate them, you need to know the direction he is faicng.
In a top-down game it could be a Vector2, a normalized Vector (a Vector of length=1), which gives you the relative movement in x and y direction. In a platformer instead it could be only a boolean, which defines if you are facing the rigth or the left. The up/down movement is then defined by jumping and other "up-forces" and the gravitation.
I think in your case it is a top-down-game, so you need a Vector2.
When you rotate your character you need to rotate the Vector2 to. To make sure, your Vector2 is normalized allways call nor() after manipulating it.
In the update or render method you should the set the x and y coordinates of your character like this:
player.x = direction.x*delta*speed;
player.y = direction.y*delta*speed;
Where delta is the Gdx.Graphics.getDeltaTime() and speed is the movementspeed of your player.
Hope it helps
All I need is to claculate the new coordinites of a player based on a click and have the player move towards it smoothly. For example player is at (20, 20) and you click at (50, 80) how would i get it to move smoothly. I have tried many different thing mostly based on the pythagorean formula trying to calculate the new coord's by finding the hypotenuse then finding the same triangle with a smaller hypotenuse but there must be an easier way.
You can:
Calculate the slope of the line segment formed by the origin and destination.
For each time period until you reach the destination, adjust the new coordinate based on the slope calculated in step 1.
Although I program in javascript, you should be able to read and understand it
function move(x1,y1,x2,y2,speed){//executed each time frame. Returns coords as array [x,y]
if(!speed)speed=1;
var dis=Math.sqrt(Math.pow(x1-x2)+Math.pow(y1-y2));
return [(x1-x2)/dis*speed,(y1-y2)/dis*speed];
}
The speed is constant at however many units per frame and it will stop when it reaches its destination. It might shake a little but that can be easily fixed.
EDIT: I forgot to mention. This function returns velocity. Not the coordinates
I really need help. I am making a game app for my final year project. It is a simple game where you have to shoot a ball into a target by rebounding of walls or angled blocks. However i need help in 2 areas:
the shooting mechanism is similar to that of stupid zombies. There is a crosshairs where you touch on the screen to indicate which direction you want the ball to be shot at. On release the ball should move into that direction and hopefully gets into the target and if not gravity and friction causes it to come to a stop.
The problem is how do I code something like this?
I need the ball to rebound of the walls and I will have some blocks angled so that the ball has to hit a certain part to get to the target. The ball will eventually come to a stop if the target is not reached.
How can I make a method to create the collisions of the wall and blocks?
I have spent the last weeks trying to find tutorials to help me make the game but have not found much specific to the type of game I am making. It would be great if sample code or template could be provided as this is my first android app and it is for my final year project and i do not have much time left.
Thank you in advance
akkki
Your question is too generic for stack overflow no one is going to do your project for you. Assuming you have basic programming experience if not get books and learn that first.
Assuming you already chose Android because of your tag, and assuming 2d game as it is easier.
Pre requests:
Install java+eclipse+android sdk if you havent already.
Create a new project and use the lunar landar example, make sure it runs on your phone or emulator.
Starting sample:
The lunar landar has a game loop a seperate thread which constantly redraws the whole screen, it does this by constantly calling the doDraw function. You are then supposed to use the canvas to draw lines, circles, boxes, colours and bitmaps to resemble your game. (canvas.draw....) Lunar landar does not use openGL so its slower but much easier to use.
Stripping the sample:
You probably don't want keyevents or the lunar spaceship!
Delete everything in the onDraw function
Delete the onKeyUp, onKeyDown
Delete any errors what happen
Create a new
#Override
public boolean onTouchEvent(MotionEvent event){
return false;
}
Run it you should get a blank screen, this is your canvas to start making your game... You mentioned balls, break it down to what a ball is: A position and direction, create variables for the balls x,y direction_x and direction_y the touch event will want to change the balls direction, the draw event will want to move the ball (adding the direction x,y to the ball x,y) and draw the ball (canvas.drawCircle(x,y,radius,new Paint())) want more balls search and read about arrays. Most importantly start simple and experiment.
2 collisions
Collisions can be done in the dodraw function and broken down to: moving an object, checking if that object has passed where it is supposed to go and if so move it back before anyone notices.... There are many differently techniques of collision detection:
If your walls are all horizontal and vertical (easiest) then box collisions checks the balls new x,y+-radius against a walls x,y,width and height its one big if statement and google has billions of examples.
If your walls are angled then your need line collision detection, you basically have a line (vector) of where your ball is heading a vector of your wall create a function to check where two lines collide and check if that point is both on the wall and within the radius of your ball (google line intersection functions)
or you can use colour picking, you draw the scene knowing all your walls are red for example, then check if the dot where the new ball x,y is, is red and know you hit
Good luck, hope this helped a little, keep it simple and trial and error hopefully this gets you started and your next questions can be more specific.