0

When VK_UP or VK_DOWN is pressed the Graphic g I created is not changing its position whatsoever. If someone could look and see if there is something wrong with my move method etc. Would really appreciate it.

Here is all my code so far:

package ping2; 
import java.applet.Applet;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;


public class Ping2 extends Applet implements Runnable, KeyListener{
final int WIDTH = 700, HEIGHT = 500;
Thread thread;
UserPaddle user1;
public void init() {


    this.resize(WIDTH, HEIGHT);
    this.addKeyListener(this);
    user1 = new UserPaddle(1);
    thread = new Thread(this);

    thread.start();


}

public void paint(Graphics g) {
    g.setColor(Color.black);
    g.fillRect(0, 0, WIDTH, HEIGHT);
    user1.draw(g);
}

public void update(Graphics g) {
    paint(g);
}








    public void run() {
    for(;;) {

        user1.move();

        repaint();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_UP) {
        user1.setUpAccel(true);
    }
    else if(e.getKeyCode() == KeyEvent.VK_DOWN) {

        user1.setDownAccel(true);
    }
}

public void keyReleased(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_UP) {
        user1.setUpAccel(false);
    }
    else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
        user1.setDownAccel(false);
    }
}

public void keyTyped(KeyEvent arg0) {


}

}

package ping2;

import java.awt.*;


public class UserPaddle implements InterfaceBar{

double y, yVelocity;
boolean upAccel, downAccel;
int player1, x;
final double FRICTION = 0.90;

    public UserPaddle(int player1) {
    upAccel = false; 
    downAccel = false;
    y = 210; 
    yVelocity = 0;
    if(player1 == 1)
        x = 20;
    else
        x = 660;
}

public void draw(Graphics g) {
    g.setColor(Color.white);
    g.fillRect(x, (int)y, 20, 80);
}

public void move() {
    if(upAccel) {
        yVelocity -= 2;
    }else if(downAccel) {
        yVelocity += 2;
    }
    //Automatically slows bar down if key not being pressed.
    else if(!upAccel && !downAccel) {
        yVelocity *= FRICTION;
    }
}
public void setUpAccel(boolean input) {
    upAccel = input;
}
public void setDownAccel(boolean input) {
    downAccel = input;
}



public int getY() {

    return (int)y;
}

}
package ping2;

import java.awt.Graphics;

public interface InterfaceBar {

public void draw(Graphics g);
public void move();
public int getY();


}
Digvijaysinh Gohil
  • 1,367
  • 2
  • 15
  • 30

1 Answers1

0

I have modified your move() a bit give it a try

move()

public void move() {
    if(upAccel) {
        yVelocity -= 2;
        y = yVelocity;
    }else if(downAccel) {
        yVelocity += 2;
        y = yVelocity;
    }
}
Digvijaysinh Gohil
  • 1,367
  • 2
  • 15
  • 30