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
}
}
Related
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).
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! :)
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.
I'm currently working on my 2D game project (Java), but so far any kind of game logic or AI has been crudely implemented. For instance, say I need to randomly position a bunch of sprites a long the top of the screen, I'd be using the Random class to do this. I'd simply use Random.nextInt( size of x axis on which to spawn ); Although this does work I'd be interested to hear how I should really be going about this kind of thing.
As a second scenario (this is why I put AI in the title, although it's not really AI), say I want to have my characters randomly blink in a life-like fashion. What I'd do here is use the Random class to calculate a % (say 20% chance) of blinking and call it every second.
Any suggestions on how I should really be going about this would be greatly appreciated.
Google for a paper titled "Steering Behaviors" by Craig Reynolds. It address just this and you'll find great ideas to start with specifically some nice ideas for giving groups of sprites the appearance of 'intelligent' movement. The key for him in his different behaviors, i.e. flocking, etc. is making properties of any given sprite dependent on those of some other sprite. You could even go so far as to say, like -- any given sprite will blink only if it's two neighbors just have blinked. Something or other along those lines.
Hope this helps!
Are you using an OOP (Object-Oriented approach)? If not, you should definitely look into it. It's really simple with java and can speed up your development time and neaten your code.
I would make a sprite class, and give them a function, say actionSpawn, or actionMove (I like to start my "action" functions with the word action so they are easily identifiable). In this function you would encapsulate the Random.nextInt function, to set the sprite's x and/or y position.
You could use the same approach to make them blink.
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.