Switch statement , only using one case at a time - java

Im trying to translate a square 'p' 5 units left or right depending on what key has been pressed . The problem is that when 'right' or 'left' is pressed it will translate 5 units in that direction but when I press again I can't move and I have to press 'left' to move right again so I never get anywhere.
Does anyone know why this is?
Task PlyThread=new Task() {
#Override
protected Object call() throws Exception {
myScene.setOnKeyPressed(event -> {
switch (event.getCode()){
//case UP: p.setTranslateY(((p.getY())-5)) ; break;
case LEFT: p.setTranslateX(((p.getX())-5)) ; break;
case RIGHT: p.setTranslateX(((p.getX())+5)) ;break;
}
});
return null;
}
};new Thread(PlyThread).start();

Ok, I assume that "Rectangle" is javafx.scene.shape.Rectangle. In this case setTranslateX() only modifies transformation matrix and does not change the rectangle coordinate X. Value of property X remains unchanged and next call to setTranslateX(getX()+5) does exactly the same job as the one before.
You need to work either with translations or with coordinates, i.e. either use setTranslateX()/getTranslateX() or setX()/getX().
Both choices may have other consequences, beyond moving rectangle on the screen, but I have no experience with JavaFX, so unfortunately I cannot elaborate more.

Related

How to make a similar animation to Flappy Bird in Libgdx?

I'm creating a game like flappy bird where the bird flaps his wings only when the screen is touched, but I'm having a problem activating the animation when the screen is touched.
batch.draw(animation.getKeyFrame(myTimeState, false), x, y); //the myTimeState is 0 to render the 1st frame only.
Then when the screen is touched I do this:
//myTimeStep is just basically a controllable timeState for the animation only
if(Gdx.input.justTouched){
myTimeState = timeState;
}else if(Gdx.input.justTouched == false && animation.isAnimationFinished(timeState)){
myTimeState = 0;
}
I don't think the animation is able to play all the frames because myTimeStep become 0 immediately after finishing to touch the screen. Also I don't think this is the right way of doing it, if you guys have better ideas or solution please help. Thanks in advance.
There are probably several ways to achieve this. You'll need to increment your timeState, of course, and also it depends how long your animation is and if you want it to loop.
If you've created your animation to play only once, and then stop (until the screen is touched again), you could simply set your myTimeState to 0 when the screen is touched, and then increment it every frame. The animation will run through and then "stop" on its own when it reaches the end (as you said no loop). The next time someone touches the screen, your myTimeState is set back to 0 and the animation starts again.
Firstly, you have to ensure your animation's playmode is set to Animation.PlayMode.NORMAL. It's a default setting, but if you set it somewhere to LOOPED, nothing would work as expected.
Secondly, I wouldn't use Input.justTouched() in this case. Instead, a listener in your input processor would be a great fit. Here's an example with Stage. If you have no idea what input processor is, here's tutorial on event handling and class documentation.
stage.addListener(new ClickListener() {
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
if(button == Input.Buttons.LEFT) {
timeState = 0;
}
return super.touchDown(event, x, y, pointer, button);
}
});
You can pick what's going to be displayed (animation's keyframe or sprite) based on result of animation.isAnimationFinished()
if(animation.isAnimationFinished(timeState)) {
//draw some sprite
} else {
//draw animation keyframe
}
I haven't checked it but there's a possibility, that this could lead to the last frame being cut out, because as soon as it gets displayed, animation.isAnimationFinished() will return true. I may be wrong, so you'll have to check it. If it becomes an issue, you can add your sprite as the last frame of your animation. When animation ends, it frezzes on the last frame, which would be your static sprite.
In both cases you'll get your animation played at the beginning of game because timeStep equal to 0. I see 2 solutions, I advise you to take the second:
Set timeStep to a large number, that is for sure larger than your animation's duration. Animation.isAnimationFinished() will then return true.
Introduce boolean variable isAnimationPlayed that:
is initialized with false,
gets set to true in your click listener,
gets set to false during isAnimationFinished(), which is called each frame only when isAnimationPlayed is true,
is used in draw() method to determine what to display.
You could just set your timeState to the duration of the animation.

Removing element from ArrayList Java Processing Boid example

Got this BOID application going in Processing with some steering algorithms.
The boids are stored
in two separate ArrayLists for each colour.
The red boid (predator) has a
pursue function:
class Creature {
int prey = 1;
PVector pursue(ArrayList boids) {
PVector steer = new PVector();
if (prey < boids.size()) {
Creature boid = (Creature) boids.get(prey);
steer = PVector.sub(boid.location, location);
steer.mult(maxpursue);
}
return steer;
}
This function gets the red boids to stand on top of the targeted white boid.
The problem is getting this white boid to disappear when all the red boids are on top of it. (Like shown in the image above)
I can add a new boid or predator with the following, but i cannot remove?:
void mousePressed() {
if (mouseButton == LEFT){
Creature predator = new Creature(mouseX, mouseY, 2);
planet.boids.add(predator);
} else if (mouseButton == RIGHT) {
Creature boid = new Creature(mouseX, mouseY, 1);
planet.boids.add(boid);
planet.boids.remove(boid); // This line does not work?
}
}
The code you posted doesn't make a ton of sense. You want to remove an existing Boid, so why on earth are you creating a new one and then immediately removing it?
You haven't posted an MCVE, so I can only answer in a general sense, but here's what you need to do:
Step 1: Refactor your code so that it makes more sense. Comment every single line if you have to, just to be sure you know exactly what the code is doing. But you shouldn't be doing things like adding a new Boid and then removing it in the very next line. Break your problem down into smaller steps, and make sure each step works perfectly by itself before trying to mix it with other funtionality.
Step 2: Create a function that takes a single white Boid and the List of red Boids, and returns true if that white Boid should be removed. Test this function by itself using hard-coded values in a standalone example sketch.
Step 3: Iterate over your white Boids and call the function you created in step 2 for each one. If the function returns true, then remove that white Boid. You might want to use an Iterator for this step.
If you get stuck on one of those steps, then post an MCVE along with a specific question, and we'll go from there. It's hard to answer general "how do I do this" type questions, but it's much easier to answer specific "I tried X, expected Y, but got Z instead" type questions- especially if we have an MCVE we can actually run on our own machines instead of some disconnected snippets.

Create Java 2D gravity?

I'm creating java game (I'm a beginner with this for now) and I'd like to start with some kind of platform game.
I'd like to know how I can make the player jump (I know how to move him up and down), but I don't know how how to make him go back down after going up.
Here is my code:
public void keyPress() {
if (listener.arrowUp) {
Jump();
}
}
private void Jump() {
if(player.get(1).getPosY() > maxJump) {
player.get(1).moveY(-10);
} else if(player.get(1).getPosY() == maxJump) {
player.get(1).moveY(85);
}
}
So.. the player moves -10px upwards as long as i press 'w' and when he hits maxJump (which is 375 and players position at the start is 465) he "teleports" back to 465 instead of sliding back down like he does when going up.. It's really hard to explain this without a video, but i hope somebody understands and can help me with this.
This question gives a basic answer to yours. Now in your jump function, you have to set the vertical_speed only once and only call fall() every frame and add some moveY.
Here are two alternatives:
Option 1. Simulating some very simple physics. You add forces to your player, so pressing the up arrow will add a force that makes the player move upwards. Gravity is constantly applied and thus it will gradually cancel out the force you applied when the up arrow was pressed. Perhaps you only want to use forces in the vertical direction you do something like this:
// Each frame
if(notOnTheGround){
verticalVelocity -= GRAVITATIONAL_CONSTANT;
}
// When user jumps
vertivalVelocity += JUMP_FORCE;
Option 2. An alternative is to kind of animate the jumps using projectile motion.
// Each frame
if(isJumping){
verticalVelocity = initialVelocity*sin(angle) - g*animationTime;
animationTime += TIME_STEP;
}
// When user jumps
isJumping = true;
animationTime = 0;
initialVelocity = ... // calculate initial velocity

Within my for loop it appears that it is ignoring if statements

I'm pretty new at java and I've been trying to write a method that draws a gradient from one configurable color to another. However, it appears that if statements inside of the for loop are being ignored.
How can I fix this? or is there something else I'm missing?
and usage of the method is:
Gradient.dVertical(Graphics,Top left corner X,Top left corner Y,Size X,Size Y,tarting Red Value,Starting Green Value,Starting Blue Value,Ending Red Value,Ending Green Value,Ending Blue Value);
EDIT: I figured out what the real problem was and I fixed it. When it should have been incremental down it was going up. So I added a couple more if statements and that cleared it up. Using random integers when calling the method did reveal another problem though. With certain values it will not finish drawing and it will just cut off in the middle. FIXED
Here's the fixed part of the code if anyone is interested
if (rrepeat == true)
{
//prevents division by zero
if(rrate!=0)
{
//for a rate that must repeat checks
//whether or not it is time to increment
check = k%rrate;
if (check==0)
{
if(ered<sred)
{
rr--;
}
if(sred<ered)
{
rr++;
}
}
else
{
rr = rr;
}
}
}
You need to be overriding the paint method.
Here's an example: Introduction to applets

How to draw a line in an IF statement for java

I am trying to program an androd application where if there is input on two places of the screen in sucsession then it will draw a line between the two points. I have already set up "X" and "Y" values that work and columns and rows are defined by the "X" and "Y" values. After those i have an IF statement that needs to draw a line between the two points. Say if column one and row two are selected and then colum one and row three are selcted I want a line to be drawn between the two points. Also I am not totally sure how to use the MotionEvent stuff or how to put the touch actions into the IF statement.
final View touchView = findViewById(R.id.touchView);
touchView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
String.valueOf(event.getX() + String.valueOf(event.getY()));
double c = event.getX();
double column = Math.floor(event.getX()/(480/12));
double r = event.getY();
double row = Math.floor(event.getY()/(630/12));
if (column == 0 && row == 2 //there should be more stuff here
) {
//I dont know how to draw a line in here, please help
}
return true;
}
});
}
Rather than explain the details here, I'll point you to these pieces of sample code from the ApiDemos sample project that comes with the SDK, that probably do exactly what you want:
DrawPoints.java
TouchPaint.java
The basic idea is to store X and Y coordinates in your touch event handler, invalidate the View, and then draw the lines in the onDraw method using Canvas operations such as drawLine.
You do neew to have a tool to draw the line, most suitable for you it seems to be Canvas. If you don't know anything about Canvas together with Android yet i suggest you to look into some examles that Android leaves us. Ones you have done that, this is going to be a simple task.

Categories