mercredi 5 octobre 2016

Java Method Variable Trouble

Vote count: 0

I am currently working on a brickbreaker game in Java that uses objects as each individual brick. In the method I use to check if the ball has hit a brick, I change the ball's Y Velocity so that it "bounces" off the brick. I'm having trouble with the communication of the Y velocity variable between my run method and check method. I use a System.out.println(yBallVel); statement in both methods and I get different values for the same variable, even though the method is called just prior to the SOP in my animation method. My Code is below. Please explain why the two variables have different values, and how I can get the check method to change the global value of the yBallVel variable. Thanks.

import java.util.*;
import javax.swing.*;
import java.awt.*; 
import java.awt.event.*;
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
public class Lemon5 extends JFrame implements Runnable, KeyListener{
int xbox;
int ybox;
static Lemon5 box1 = new Lemon5();
static Lemon5 box2 = new Lemon5();
Container con = getContentPane();
Thread t = new Thread(this);
int xPaddleLoc;
int yPaddleLoc;
int xBallLoc;
int yBallLoc;
int xBallVel;
int yBallVel;
int xBallBottomLoc;
int yBallBottomLoc;
boolean draw;

public void boxvalue(int xbox, int ybox){
this.xbox=xbox;
this.ybox=ybox;
}
public Lemon5()
{
xPaddleLoc=270;
yPaddleLoc=530;
xBallLoc=100;
yBallLoc=400;
xBallVel=0;
yBallVel=-5;
draw=true;

xBallBottomLoc=xBallLoc+25;
yBallBottomLoc=yBallLoc+50;
con.setLayout(new FlowLayout());
addKeyListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
t.start();
}
public void check(int yBallVel){
if(xBallBottomLoc>=this.xbox&&xBallBottomLoc<=this.xbox+75
&&yBallLoc<=this.ybox+    75){
yBallVel=500;
System.out.println(yBallVel);
}

}
public void run()
{
try{
while(true)
{
xBallBottomLoc=xBallLoc+25;
yBallBottomLoc=yBallLoc+50;
if(xPaddleLoc<0){//Left Paddle Threshold
xPaddleLoc=0;
}
if(xPaddleLoc>500){//Right Paddle Threshold
xPaddleLoc=500;
}
if(xBallLoc<=0){//Left Wall Bounce
xBallVel=10;
}
if(xBallLoc>=550){//Right Wall Bounce
xBallVel=-10;
}
if(yBallLoc<=0){//Top Bounce
yBallVel=5;
}
if(yBallBottomLoc==yPaddleLoc&&xBallBottomLoc<=
xPaddleLoc+100&&xBallBottomLoc>=x    PaddleLoc){//Paddle Bounce
yBallVel=-5;
}
box1.check(yBallVel);
System.out.println("asdf "+yBallVel);
xBallLoc=xBallLoc+xBallVel;
yBallLoc=yBallLoc+yBallVel;
t.sleep(17);
repaint();
}
}
catch(Exception e)
{
e.printStackTrace();
}

asked 16 secs ago

Let's block ads! (Why?)



Java Method Variable Trouble

Aucun commentaire:

Enregistrer un commentaire