Moving images with the arrow keys in Java - java

I am writing a small game in java and an obvious key component is being able to move the character with the arrow keys. However I cannot get all directions to work, and only the last two if statements of the following block actually activate.
public void Update(){
if(Canvas.keyboardKeyState(KeyEvent.VK_UP))
yVel = -1;
else
yVel = 0;
if(Canvas.keyboardKeyState(KeyEvent.VK_LEFT))
xVel = -1;
else
xVel = 0;
if(Canvas.keyboardKeyState(KeyEvent.VK_DOWN))
yVel = 1;
else
yVel = 0;
if(Canvas.keyboardKeyState(KeyEvent.VK_RIGHT))
xVel = 1;
else
xVel = 0;
x += xVel;
y += yVel;
}
My inputs are good, all keys are registering, but no math is taking place. If anyone has suggestions or a library/package that would make this easier, please let me know.

You override the values in the else blocks. You maybe want to do this.
public void Update(){
xVel = 0;
yVel = 0;
if(Canvas.keyboardKeyState(KeyEvent.VK_UP)) {
yVel -= 1;
}
if(Canvas.keyboardKeyState(KeyEvent.VK_LEFT)) {
xVel -= 1;
}
if(Canvas.keyboardKeyState(KeyEvent.VK_DOWN)) {
yVel += 1;
}
if(Canvas.keyboardKeyState(KeyEvent.VK_RIGHT)) {
xVel += 1;
}
x += xVel;
y += yVel;
}

Its very obvious. Everytime your loop gets executed it happens something like this:
If it executes the first if statement, it also executes the rest of the else statements.
it should be something like this:
xVal = 0;
yVal = 0;
if(keyDown){
yVal++;
}
else if(keyUp){
yVal--;
}
else if(keyLeft){
xVal--;
}
else{
xVal++;
}
//Your rest of the code.

Related

Bouncing Ball (in class) - need help coding array

I'm all new to this and doing a beginner's lecture on Java (with Processing). Our assignment this time is the bouncing ball. I've (sort of) successfully gotten it to move the way it's supposed to and put it into a class, but I can't get the array right.
Here's the version using the class:
class Ball {
float x;
float y;
float ySpeed;
float gravity;
int counter = 0;
Ball()
{
x = 300;
y = 300;
ySpeed = 2.5;
gravity = 0.2;
}
void move()
{
y = y + ySpeed;
ySpeed = ySpeed + gravity;
if (y > height-25 )
{ySpeed = ySpeed * -0.85;
y = height-25;
counter++;
}
println(counter);
if(counter >= 17)
{ySpeed=0;
y=height-25;}
}
void display()
{
ellipse(x,y,50,50);
}
}
//using the class:
Ball b1;
void settings()
{
size(800,600);
}
void setup()
{
b1 = new Ball();
}
void draw()
{
background(0);
b1.move();
b1.display();
}
Here's what I ended up with after messing it up completely.
//class Ball
class Ball {
float[] x;
float[] y;
float[] ySpeed;
float[] gravity;
int i;
int counter = 0;
//constructor
Ball()
{
x[i] = 300;
y[i] = 300;
ySpeed[i] = 2.5;
gravity[i] = 0.2;
}
void move()
{
y[i] = y[i] + ySpeed[i];
ySpeed[i] = ySpeed[i] + gravity[i];
//changes direction; (-25) to avoid movement beyong boundary
if (y[i] > height-25 )
{ySpeed[i] = ySpeed[i] * -0.85;
y[i] = height-25;
}
println(counter);
if(counter >= 17)
{ySpeed[i]=0;
y[i]=height-25;}
}
void display()
{
//draw ellipse
ellipse(x[i],y[i],50,50);
}
}
//using the class
final int i = 9;
Ball[] Balle = new Ball[10];
void settings()
{
size(800,600);
}
void setup()
{
Balle[i] = new Ball();
for (int i = 0; i < Balle.length; i++)
{Balle[i] = new Ball(x[i],y[i],50,50), i*4);
}
}
I suppose this looks weird because it's picked together from several different help pages... the current error is "variable x does not exist" on
{Balle[i] = new Ball(x[i],y[i],50,50), i*4);
I'm aware there are several other problems.
Right now I'm quite lost in figuring out how it works. Could somebody give me a hint?
variable x does not exist - It's because you don't have x as a global variable, but as a class variable, which is therefore only accessible from within the Ball class or by an instance of the Ball class. I don't exactly know why you're using arrays for x and y, primitives would do just fine. And don't forget to add the draw() method, as in processing, that serves as the 'main loop', it gets executed every 0.x sec (frameRate) so you MUST use that as well. Your other functions like display() etc.. can also be called from within the draw function.
Geez, what did I even do there?
Here it is:
Ball[] balls = new Ball[10];
void settings()
{
size(600,800);
}
void setup()
{
for (int i = 0; i < balls.length; i++)
{
balls[i] = new Ball();
}
}
void draw()
{ background(0);
for (int i = 0; i < balls.length; i++)
{
balls[i].move();
balls[i].display();
}
}
Is programming like that, stumbling around in the dark until you get hit by a brick...?
Here's a pseudo code.
If ball <= bottom, reverse the speed of ball.
(That means when it hits the floor, the speed reverses. Multiply it with -1)
Other wise, speedOfBall = speed - (gravity*time);
You can easily calculate the displacement in terms of coordinates as s = velocity*time + .5*gravity*time^2.

Libgdx Accelerometer not working?

for some reason the block is not moving when I tilt the screen, and I don't know what's wrong. Just to clarify, I set the cfg.accelerometer to true, but the cfg.compass to false. Here's the source code-
public void update()
{
x += velX;
y += velY;
//movement
//left
if (Gdx.input.isKeyPressed(Keys.LEFT))
{
velX = -speed;
}
//right
if (Gdx.input.isKeyPressed(Keys.RIGHT))
{
velX = speed;
}
//up
if (Gdx.input.isKeyPressed(Keys.UP))
{
velY = -speed;
}
//down
if (Gdx.input.isKeyPressed(Keys.DOWN))
{
velY = speed;
}
if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer))
{
velX = Gdx.input.getAccelerometerX();
velY = Gdx.input.getAccelerometerY();
}
//stop
if (!Gdx.input.isKeyPressed(Keys.LEFT) && !Gdx.input.isKeyPressed(Keys.RIGHT))
{
velX = 0;
}
if (!Gdx.input.isKeyPressed(Keys.UP) && !Gdx.input.isKeyPressed(Keys.DOWN))
{
velY = 0;
}
//collision with edges of screen
if (x <= 0)
{
x = 0;
}
if (x >= 1920 - width)
{
x = 1920 - width;
}
if (y <= 0)
{
y = 0;
}
if (y >= 1080 - height)
{
y = 1080 - height;
}
long recoveryElapsed = (System.nanoTime() - recoveryTimer)/1000000;
if (recoveryElapsed > 2000)
{
recovering = false;
recoveryTimer = 0;
}
System.out.println(lives+ " lives, recovering, "+recovering);
}
Help would be much appreciated, thanks. There are no tutorials that I have found with a working example shown, so I don't really know if what I am doing is correct, but I can't see anything wrong with it.
You are setting the Accel values, and then if the keys are not pressed you are setting them to 0 again. Do it like this:
//stop
if (!Gdx.input.isKeyPressed(Keys.LEFT) && !Gdx.input.isKeyPressed(Keys.RIGHT))
{
velX = 0;
}
if (!Gdx.input.isKeyPressed(Keys.UP) && !Gdx.input.isKeyPressed(Keys.DOWN))
{
velY = 0;
}
if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer))
{
velX = Gdx.input.getAccelerometerX();
velY = Gdx.input.getAccelerometerY();
}

Character collision when hits edges of window

I'm having troubles having my character stop once it hits the edges of the windows.
Here's my update method.
public void update(GameContainer gc, StateBasedGame sbg, int delta)
{
Input input = gc.getInput();
playerX += VelocityX;
gc.setShowFPS(Splash.showFps);
if(input.isKeyPressed(Input.KEY_F1))
{
Splash.showFps = !Splash.showFps;
}
if (input.isKeyDown(Input.KEY_RIGHT))
VelocityX = 10;
else if (input.isKeyDown(Input.KEY_LEFT))
VelocityX = -10;
else if (playerX >= 700)
VelocityX = 0;
else
{
VelocityX = 0;
}
}
I realize going off to left is occurring because I haven't coded it yet but the character goes off the screen the right
if (input.isKeyDown(Input.KEY_RIGHT)){
VelocityX = 10;}
else if (input.isKeyDown(Input.KEY_LEFT)){
VelocityX = -10;}
else{VelocityX = 0;}
if (playerX >699){
playerX=699;
VelocityX = 0;}
else if(playerX<1){
playerX=1;VelocityX = 0;
}
Problem fixed. Within the key detection you set the velocity to 0.
So instead
if (input.isKeyDown(Input.KEY_RIGHT))
VelocityX = 10;
else if (playerX >= 700)
VelocityX = 0;
Do something like
if (input.isKeyDown(Input.KEY_RIGHT))
{
VelocityX = 10;
if (playerX >= 700)
VelocityX = 0;
}
There are a couple things wrong I noticed. The first is your update issue: you want to player to move by their velocity. You also need to do your bounds checking. Another problem you have, that others haven't noted on, is that you have a right key preference, That means that if you are holding the right and left key, the player moves right. This is due to the if / else if statements. You should separate your ifs out for a more granular level of control:
public void update(GameContainer gc, StateBasedGame sbg, int delta)
{
Input input = gc.getInput();
//playerX += VelocityX; -> this is moved
gc.setShowFPS(Splash.showFps);
if(input.isKeyPressed(Input.KEY_F1))
{
Splash.showFps = !Splash.showFps;
}
VelocityX = 0;
if (input.isKeyDown(Input.KEY_RIGHT))
VelocityX += 10;
//removed the else
if (input.isKeyDown(Input.KEY_LEFT))
VelocityX -= 10;
//you want to bounds check regardless of the above statments
//get rid of the else
if ((playerX >= 700 && VelocityX > 0) || (playerX <= 0 && VelocityX < 0)) //check both sides
VelocityX = 0;
//move the player
playerX += VelocityX;
}
EDIT: Modified my code to fix the issue of being unable to move when at a boundary.

Move tile by tile with dynamic speed

I'm using java with slick2d library and trying to move tile by tile with dynamic speed. I have tried a couple methods but none of them can move with dynamic speed between the tiles. Can someone help me with that and give some examples?
edit:
this two methods have I tried
move with out delta
movementSpeed = 2;
//decide direction
if(targetX != x)
{
animation.update(delta);
if(originalX < targetX)
x += movementSpeed;
else if(originalX > targetX)
x -= movementSpeed;
}
if(targetY != y)
{
animation.update(delta);
if(originalY < targetY)
y += movementSpeed;
else if(originalY > targetY)
y -= movementSpeed;
}
lerp
public static float lerp(float start, float stop, float t)
{
if (t < 0)
return start;
return start + t * (stop - start);
}
public void move(long delta)
{
if (procentMoved == 0)
{
if (getSpeed(targetX, targetY) != 0)
{
movementSpeed = getSpeed(targetX, targetY);
} else
{
targetX = originalX;
targetY = originalY;
}
}
if (procentMoved < 1)
{
animation.update(delta);
// movementSpeed = getSpeed(targetX, targetY);
procentMoved += movementSpeed;
} else if (procentMoved > 1)
{
animation.update(delta);
//TODO fix bouncing bug
procentMoved = 1;
}
+ movementSpeed);
x = lerp(originalX, targetX, procentMoved);
y = lerp(originalY, targetY, procentMoved);
if (x == targetX)
;
originalY = x;
if (y == targetY)
;
originalY = y;
}
It seems as if this could be your issue. Your if statements are just closing and not really doing its part. Also, you're variables are mixed up as well.
if (x == targetX)
; // This will skip the If statement
originalY = x;
if (y == targetY)
; // This will skip the If statement
originalY = y;
}
In all reality you're saying
orginalY = x; // Y = X?
orginalY = y; // Y = Y
Please do not take this to heart. I'm still having this issue as well, however I'm having to do some corrections and auto placements in order for this to work correctly.

Nokia N97 Related to sensor Api and some java logic

Myself shweta dodiya.I am having an problem related to sensor and logic in j2me which i had implemented for achieving the result in my project.The logic which i had implemented is as follows:-
sensor= (SensorConnection) Connector.open("sensor:acceleration");
try {
data = sensor.getData(1);
} catch (IOException ex) {
ex.printStackTrace();
}
for (int i = 0; i < data.length - 1; i++) {
value[i] = data[i].getDoubleValues()[0];
}
CurrentValX = value[0];//X-axis of sensor
CurrentValY = value[1];//y-axis of sensor
if (CurrentValX < PreValueX1) {
left = false;
right = true;
} else if (CurrentValX > PreValueX1) {
left = true;
right = false;
}
if (CurrentValY < PreValueY1) {
down = false;
up = true;
} else if (CurrentValY > PreValueY1) {
down = true;
up = false;
}
if (right == true && ballX < Scrwidth - 15) {
ballX += 4;
} else if (left == true && ballX > 15) {
ballX -= 4;
}
if (down == true && ballY < Scrheight - 15) {
ballY += 4;
} else if (up == true && ballY > 15) {
ballY -= 4;
}
CurrentValY = PreValueY1;
CurrentValX = PreValueX1;
//check for the collision of ball with the other object like brick
if (bricksprite.collidesWith(ballSprite, true)) {
if (right) {
ballX -= 10;
}
if (left) {
ballX += 10;
}
if (up) {
ballY += 10;
}
if (down) {
ballX -= 10;
}
}
The problem i am having is in the collision of the ball and the bricks.when it get collide i want to move ball in the opposite direction of the collision.But sometime the ball instead of moving in opposite direction it keep moving in same direction.I had getting the direction of the ball through the boolean up,down,left,right.
Please help me to solve it and guide me and correct me if i m wrong somewhere
Thanks in advance
I haven't read your code , But in past I have coded the same kinda game,
In that I have applied following logic;
1.when ball colides suppose consider ball is moving from right to left than collides at left wall at some angel. here your x and y was decreasing in uniform manner upon colission your x should increase while y should be decreasing with the same fashion.
2.when ball colides vertical wall , y should invert x should be same..
I hope it clears up the logic.

Categories

Resources