Twitchy Sprite Movement (Java) - 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! :)

Related

RayCast algorithm in Bukkit

I've been wondering if it would be possible in a Bukkit plugin to create a RayCast system that I could use to, off a Vector, create a ray that I could, for instance, summon particles every so many blocks along it. I don't have much experience with math; I am only in eighth grade geometry and haven't gotten to trig yet. I didn't want to use player.getTargetBlock() and player.getLineOfSight() because they are deprecated and getLineOfSight() only gives me a List of Blocks, and I was looking for something that i could get a List of Locations or something like that and to be able to change the distance interval between each Location in the list.
Thanks. I hope I can get a solution for this. I know people have done it before, but when I search up RayCast Algorithms, it mainly gives me ways to write a Doom-like game engine.
Looks like I have found a solution, here it is if you want to know it. It is a test plugin, so, for testing, i added a /vec command to check your vector and the /shoot command shoots a particle. The args are /shoot [length of ray] [space between particles in blocks]. The length cannot be a decimal (it probably could with some code changes) but the space between the particles can. To stop the particle at a solid block, I would just break the loop when lastParticle.getBlock().getType().isSolid() is false.
http://pastebin.com/CvE5vG8U
P.S. I used darkbladee12's ParticleEffect library for this, I could just use the Effect class, but that only has a couple of effects.
To iterate threw blocks, you can use a BlockIterator:
LivingEntity from;//set this to the living entity (or player) that you would like to send the particles from
int distance;//set this to the distance, in blocks, that you would like the particles to go
BlockIterator blocksToAdd = new BlockIterator(from.getEyeLocation(), 1, distance);
while(blocksToAdd.hasNext()){
Location loc = blocksToAdd.next().getLocation();
if(!loc.getBlock().getType().isSolid()){
//stop playing particles if the next block is not solid
break;
}
else{
//play the particle here using the location loc
}
}

Let an Enemy follow a path with the same speed

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).

Easiest way to do collision LWJGL JAVA

Ok so I have a ArrayList which contains all the tiles that need to be drawn to the screen and I have the player that is moved with the arrow keys, but I am unsure how I could implement collision detection with this, Would it be efficient to check if the current tile is filled and if so stop, This is my first time creating a game from scratch so any help is greatly appreciated!
EDIT:
The tiles are 32x32 images which are held in a ArrayList basically if you guys can help me with the y-axis collision i should be fine with the rest.
Tile class contains x, y, and the tile type
EDIT2:I havent tried anything yet, I don't really know where to start but basically i need some sort of Collision on tile, e.g While player is moving if collide on tile do something but i dont know how to check if i have collided or not
Below I have an example of a bouncing ball, which will test for the end of the JPanel, and do something
//x = X-Axis Location //This tests for a collision of the JPanel on the left side or the right side
public boolean isLeavingSideToSide(JPanel jp)
{
if( x <=0 || x+ width >= jp.getWidth())
{
BounceEvent be = new BounceEvent(this);
notifyListeners(be);
return true;
}
else
return false;
}
BounceEvent is created to allow for the notifyListener, which calls the bounced method.
public void notifyListeners(BounceEvent be)
{
for(BounceListener bl : listeners)
{
bl.bounced(be);
}
}
My Bounced method changes the color of the ball (Does some action)
public void bounced(BounceEvent be) {
Ball b = be.getBall();
Color c = b.getColor();
int x = 256;
int newColor1 = (int) (Math.random() * x);
int newColor2 = (int) (Math.random() * x);
int newColor3 = (int) (Math.random() * x);
b.setColor(new Color(newColor1,newColor2,newColor3));
}
Hopefully this will help you get started.
Collision detection isn't matter for beginners, nor can it be fully explained in a Stackoverflow post; if you're still struggling with arrays, try to make simple games, where collision is detected by calculating the distance between objects like circles.
There are many ways to handle collision detection, but you have to be more specific:
what kind of tile-based game are you planning to develop?
I strongly suggest you to read this article, by Katy Coe, which gives a summary of a few implementations. The following methods are explained in the aforementioned blog.
The simplest and most intuitive method is the Pixel Colour Approach, where players can move on tiles with a specific color value, but it can be used only with a limited color palette. The Mask Approach is essentially the same as PCA, but it hides black and white layers behind custom graphics; the latter is computationally expensive and not generally recommended.
The Grid-Based Approach is probably what you're looking for. Each element of the map corresponds to a tile of the grid (described by a 2D array). The player moves in a discrete space, although animation might fake fluid movements.
The Pixel Tile Method describes collisions by sorrounding characters with n control points; this approach let the developer use non-squared characters in a tiled world.
The Bounding Box Method is a simpler implementation of PTM, where the player is wrapped in a rectangle. The program checks whether any of the four corners of the rectangle intersect with any wall.
Discrete Collision Detection, or its improved version, Speculative Contacts, are used in more complex games and you surely don't need those now.
Don't try to learn all at once, start with the simplest implementation you can think of.
Otherwise, you would soon get discouraged and would not appreciate the pro/cons of each technique.
I've recently found this great tutorial about tile-based games with Macromedia Flash, but you can easily apply those techniques using your language of choice. READ IT!
If you want an alternative to Katy's articles, Rodrigo Monteiro comes in help.

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.

How would one implement an FPS camera?

So I'm currently working on some FPS game programming in OpenGL (JOGL, more specifically) just for fun and I wanted to know what would be the recommended way to create an FPS-like camera?
At the moment I basically have a vector for the direction the player is facing, which will be added to the current player position upon pressing the "w" or forward key. The negative of that vector is of course used for the "s" or backward key. For "a", left, and "d", right I use the normal of the direction vector. (I am aware that this would let the player fly, but that is not a problem at the moment)
Upon moving the mouse, the direction vector will be rotated using trigonometry and matrices. All vectors are, of course, normalized for easy speed control.
Is this the common and/or good way or is there an easier/better way?
The way I have always seen it done is using two angles, yaw and pitch. The two axes of mouse movement correspond to changes in these angles.
You can calculate the forward vector easily with a spherical-to-rectangular coordinate transformation. (pitch=latitude=φ, yaw=longitude=θ)
You can use a fixed up vector (say (0,0,1)) but this means you can't look directly upwards or downwards. (Most games solve this by allowing you to look no steeper than 89.999 degrees.)
The right vector is then the cross product of the forward and up vectors. It will always be parallel to the ground plane since the up vector is always perpendicular to the ground plane.
Left/right strafe keys then use the +/-right vector. For a forward vector parallel to the ground plane, you can take the cross product of the right and the up vectors.
As for the GL part, you can simply use gluLookAt() using the player's origin, the origin plus the forward vector and the up vector.
Oh and please, please add an "invert mouse" option.
Edit: Here's an alternative solution which gets rid of the 89.9 problem, asked in another question, which involves building the right vector first (with no pitch information) and then forward and up.
Yes, thats essentially the way I have always seen it done.
Yeah, but in the end you will want to add various other attributes to the camera. To spell it n00b: keep it tidy if you want to mimic Quake or CS. In the end might have bobing, FoV, motion filtering, network lag suspension and more.
Cameras are actually one of the more difficult parts to make in a good game. That's why developers usually are content with a seriously dull, fixed 1st/3rd person ditto.
You could use Quaternions for your camera rotation. Although I have not tried it myself, they are useful for avoiding gimbal lock.

Categories

Resources