Let an Enemy follow a path with the same speed - java

I started programming a game in java. I have Enemys and a Player, a basic 2D game, thats to get experience for the first time.
Now i wanted the Enemys to follow a path, which i can draw in to a "level editor".
I have a JPanel, a mouseMoveListener, and on click the Path2D starts saving the mouseMove Points to a Path2D.Double Object.
After that, i implemented the following method to make the enemys following this path:
public void forward(){
if(!pathIterator.isDone()){
pathIterator.currentSegment(current);
x = current[0];
y = current[1];
pathIterator.next();
}
else {
dead = true;
}
}
I think its clear what happens now: The Enemy is following, but the speed is that i moved the mouse with. So if i move to Mouse to fast, the enemy just.. "jumps" from one point to an other. To slow, its "sneaking" over that points. (And because im not an Robot, i cannot move the Mouse with the same speed ^^)
Talking of Robot: Yes, i could let a awt.Robot move my Mouse. But this isnt really possible too, because i have to draw complicated paths, which dont have any visible mathematics behind.
So, i want let this Enemys to move on this path with the same speed. My Problem: I don't know where to implement a "fix". I have 2 Ideas:
Maybe i could work on the Path creation: Instead of just adding the Points to the Path2D, maybe i could calculate points between the points where i moved to fast, or deleting points which are to near by each other. But: First, I don't know how to calculate this, (Is there any maths logic to achieve this?) And Second, when i do this i probably would'nt be able to change the speed of the enemys ingame, and that would be bad
The second idea i have, is to calculate the points between (oder the points to jump over), this should happen every frame, relative to the actual speed. But here im not experienced enough in maths to.
So, are that ways possible, and if yes, has someone an idea how to calculate this?
And, if not, what other possibilitys i have to achieve this?
Thank you, and sorry for the bad english!

All you need to do is define the speed of movement of the enemy inside the enemy class.
When it works out the next point to move to then create a direction vector by subtracting the current position from the new position.
Normalize the direction vector (so it is length 1) then multiply it by the speed and the tpf (time per frame).
Move by that amount instead of jumping to the next point.
(Note if the points are very close together or the framerate is low this can cause it to overshoot a bit, it should be fine though).

Related

Twitchy Sprite Movement (Java)

I'm having an issue with sprite movement, and I'm not sure how to deal with it.
When I set a destination for my player sprite (by clicking the screen), it sets the player moving in that direction. Unfortunately, the player sort of... oscillates. He sort of shivers along the path.
I've set up a test project using just graphics primitives (graphics.fillRect(x,y,w,h)), and its really easy to see. Here's a sort of example without using video/gifs:
My code looks like this
public void tick() {
if (InputHandler.leftClick.heldDown) {
dest.setLocation(InputHandler.leftClick.xPos, InputHandler.leftClick.yPos);
}
direction.setLocation(dest.getX() - position.x, dest.getY() - position.y);
direction.normalize();
position.add(direction.multiply(velocity));
}
This is a really really basic movement system because I'm having the same issues elsewhere and I wanted to work on them in a more controlled environment.
The weirdest part about this is that when the player arrives, he still just sits on one point, shivering madly.
Can anyone help?
There's a little discrepancy? between what you said, "clicking on the screen" and heldDown. Have you read about mouse event handlers? But I see that you want to go on a tick by tick basis. It would be more clear to have a boolean flag that alerts you if the path was changed. Then this segment would look like
if (leftclicked) {
dest.setLocation(InputHandler.leftClick.xPos, InputHandler.leftClick.yPos);
leftclicked = false;
}
...
Strictly, in physics, velocity is a vector. It has both direction and magnitude. If you intend this as simply a speed at which the thing can move, with instant turning, the next three lines should be fine, although the readability seems improvable. (You have to be sure of what all the helper methods are doing. I'd probably prefer to do whatever calculations needed right here in one place.)
However I suspect you do have velocity as something like vector. There is some notion of momentum in here. I think the multiply() method is implemented strangely. If it adds/combines the angle of velocity with the angle of direction behavior like this results. Having an aspect of momentum is cool but if desired you should really think how to do it.
Another explanation is that the code you've shown works as intended, inching the thing along the direction of the black line, but some other part of your code is messing with position. We weren't given a picture of what happens on arrival...
One more thing about readability. It's very important..."really really basic" things can be buggy swamps without simple organizing steps. I have to rewrite implementations several times because I get overeager and miss designs. It looks like you are doing well at my bane, the "one method/object does one thing (well)" principle but getting into trouble with...naming, of all things. Example: direction.setLocation() Now, directions do not have locations. Repeat: directions do not have locations. Also, directions don't need to be normalized - they don't have lengths.
Instead:
direction = new Direction(dx, dy);
position.add(direction.multiply(MOVEMENT_SPEED));//assuming constant speed
where
//sensible encapsulation of "direction"
class Direction {
double angle;//angle in degrees
//constructs a direction from cartesian coordinates
Direction(int x, int y){
angle = Math.toDegrees(Math.atan((double)y/x));
}
//create a vector of specified length in this direction
java.awt.Point multiply(double amt){
return new java.awt.Point(amt*Math.cos(angle), amt*Math.sin(angle))
}
...
}
Hmm long answer...please try for crystal clear code and questions in future! :)

Collision detection between ball & maze made dynamically from text file

Ok so I am creating a ball tilting game, where you navigate a ball around a maze. The ball works, and is all good in the area however I am having some problems in the maze.
The maze is programmatically created through a .txt file that contains 1's and 0's (1's being walls, and 0's being floor.) I have a for loop that goes through the whole .txt file and places a white(wall) or black(floor) square at the proper coordinates on a canvas. This is similar to the apps-for-android Amazed game if you have seen it link. However, instead of placing wall-type detection on his tiles, he just resets the game and deducts a life point if the user rolls onto a 'void' tile.
However I am looking to have 'walls' and not 'voids'. Where if the ball touches the wall, it doesn't go beyond that point, but can still move freely on the other axis. Unless it hits a corner, of course.
The problem I am having is actually creating this detection. I have tried a number of ways but nothing so far has been successful or useful.
I have tried:
- Have an ArrayList of all of the coordinates of the wall tiles, and every game tick, it checks to see if the ball is touching one. However this just slowed the game down to a crawl and was just extremely terrible.
- Check to see what tile the ball is on, and if it's on a wall tile, to stop it on an axis but let it move freely on the other, however this still didn't work as there were some issues when the ball was to the right of the wall tile, but also under it, it couldnt move up, as the code detected it being under the ball.
And a few other ways but I really cannot remember! It's been a bit hectic.
So, I am asking, if anyone has any experience in this area could they please give me a push in the right direction? Im hoping to have the maze walls sorted by Tuesday however it's looking grim!
If you need any more information, please ask.
Thank you in advance for any and all replies.
Instead of having an ArrayList that you have to iterate over, why not store the maze the same way you do the text file? Use a 2D boolean array filled with true for wall and false for floor, or vice versa.
This simplifies finding a wall considerably. All you have to do is figure out where in your grid the ball is. Then you can just check the cells immediately surrounding it. Even if you include diagonals(which probably isn't necessary for an all-90-degree maze), this equates to checking 8 booleans from an array, basically instant.
As for the axis issue, just stop movement in that direction. No need to freeze a whole axis. For instance, if the wall is right of you, just don't allow x to go higher. No reason to not let it lower unless there's a wall to the left.
This is just a general idea, though. Since it's homework, no code for you ;)
Edit:
The 2D array is just that, a boolean[][] which holds true in each of the spots where you want a wall to be. When you read in your text file, just assign it straight away.
Assuming each line in your text corresponds to an y row, and each 0/1 is the x for that column, when you read a 1, assign map[x][y] = true.
I'm honestly not sure what else you need elaboration on. It's a common format to do simple tile-based maps, though. If you google "2d array tile map", you'll find several resources to help with it.

Implementing AI to hide behind obstacles

I am developing an AI simulation of predator and prey. I would like to simulate the AI hiding behind obstacles, if it is being chased. But I am still trying to figure out the best way to implement this.
I was thinking along the lines of checking on which side of the obstacle the predator is on and trying to go on the opposite side. Maybe using the A* path finding algorithm to ensure that it gets there using the shortest path.
Now the main reason I am writing is in case somebody is able to point me in the right direction of implementing this (maybe somebody has done this before) or have any other good ideas how to implement it. I have never done anything like this before in terms of programming AI or making any game.
All the obstacles are either horizontal or vertical squares/rectangles.
Please note that the circle in red is the predator while the circle in green is the prey being chased.
I can't give any code off the top of my head, but I can tell you a few things:
First, you need to define the goal of this program. For this case, it is to get the AI to hide behind an obstacle, keeping the user and the AI on opposite sides whenever possible.
Next, you need to decide what needs to be done inside the code (without writing any real code) to accomplish this goal. For instance:
We need to determine what "zone" of the scene is considered "behind the obstacle"
Next, we need to determine a path for the AI to get to that zone without going through the obstacle.
Lastly, we need to add some sort of delay to this so the AI doesn't constantly change its mind for every pixel the user moves across the screen
This isn't per se an easy problem, but it is certainly achievable without breaking too much of a sweat. I'd recommend you find a way, even if it is slow and requires a ton of code, then write the code for it, and lastly refine. If you worry about refinement, then you never get any of the problem solved.
HINT: Determine a vector that points from the player to the middle of the obstacle. Then, multiply the vector by 2 and add it to the position of the player and that gives you a point on the other side of the obstacle (assuming it is a rectangle). Apply a Math.min() or Math.max() restrictor to the x and y values you get to keep the AI as close or far from the obstacle as you wish. That should be a decent start! :)
Update -- I decided to add some code!
// This assumes a few variables:
int obstacleCenterX, obstacleCenterY;
int aiX, aiY, aiWalkSpeed;
int predatorX, predatorY;
private void updateAIMovement() {
int slope_x = obstacleCenterX - predatorX;
int slope_y = obstacleCenterY - predatorY;
int destination_x = predatorX + (slope_x * 2);
int destination_y = predatorY + (slope_y * 2);
if(aiX != destination_x){
aiX += (slope_x / Math.abs(slope_x)) * aiWalkSpeed;
}
if(aiY != destination_y){
aiY += (slope_y / Math.abs(slope_y)) * aiWalkSpeed;
}
}
I have not tested anything at all, but I think this might be somewhat of a right path to take. I could have done A LOT to improve just that little code snippet, but I didn't (such as some trig to make sure the player moves at a true speed when going diagonally, etc...)
Hopefully this helps a little!
I would check if there is something crossing the direct line between x and each observer. If it is, x is hidden.

collision & touch + shoot methods for Android

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.

How to animate Rectangle on a Path2D object in Graphics2D context

I have just started learning basics about Graphics2D class, So far I am able to draw different objects and implements ActionListener to actually move them on screen by onKeyPress. So far so good, While I thought of doing something more complicated. I want to give a path to my object and animate it on that particular path only.
Something like, I will draw a line on sky and a plane should stick with that drawn line and keep it self to fly on that particular line. Now is it possible?
I don't need any sort of code, But few different method or ideas will let me get started working on this. A visualise elaboration of my idea is as below.
Start Point :
End Point :
Now as shown above, my yellow box(in future plane) should stick with given path while animating(path grey line)
My research so far,
I have searched my buzz words such as path in java, and found Path2D and GeneralPath classes, Does anyone know if I can use that to solve this.
Thanks
Great !
It reminds me of my first steps in IT. How much I enjoyed all this simple math stuff but that make things move on screen. :)
What you need is actually a linear interpolation . There are other sorts of interpolation and some api offer a nice encapsulation for the concept but here is the main idea, and you will quite often need this stuff :
you must rewrite your path
y = f (x )
as a function of time :
at time 0 the item will be on start position, at time 1 it will reach the end. And then you increment time (t) as you wish (0.001 every ms for instance).
So here is the formula for a simple linear path :
x = xstart + (xend-xstart) * t
y = ystart + (yend-ystart) * t
when t varies, you object will just move linearly along the path, linearly has speed will be constant on all the path. You could imagine some kind of gravtity attraction at end for instance, this would be modeled by a quadratic acceleration (t^2 instead of t) ...
Regards,
Stephane
First, make the ability to move from point a to point b. This is done with simple algebra.
Second, make the ability to take a path and translate it into points. Then when you're going to do curves, you're really just moving from point to point to point along that curve.
This is the most elementary way to do it and works for most instances.
What your talking about is simple 2D graphics and sprites. If that is all you need then for Java take a look at Java 2D Sprites If your leaning more towards or will eventually go with camera perspectives and wanting to view the animation from diferent angles the go with Java 3D from the OpenSource Java 3D.org. Either way what you want is a simple translating of the object along a line, pretty simple in either 2D or 3D.
You can try going trough the code of my open source college project - LANSim. It's code is available in Code menu. It does similar to what you are trying to do.

Categories

Resources