Reputation: 670
I am very new to Java and programming in general, so I tried to write a simple program whose only job is to make a ball moving around with the arrow keys and jumping with the space button. The program compiles but the ball doesn't move.
I probably didn't fully understood the Applet principles, could you explain to me the mistake I made?
Applet:
package test_game;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Starting_Point extends Applet implements Runnable, KeyListener {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 700;
private static final int HEIGHT = 300;
Character Phil;
Thread thread;
@Override
public void init() {
setSize(WIDTH,HEIGHT);
Phil = new Character(50, 200);
}
@Override
public void start() {
thread = new Thread(this);
thread.start();
}
public void run() {
while (true) {
repaint();
}
}
@Override
public void paint(Graphics arg0) {
Phil.paint(arg0);
}
@Override
public void keyPressed(KeyEvent arg0) {
switch (arg0.getKeyCode()) {
case (KeyEvent.VK_LEFT): Phil.setX(Phil.getX() - Phil.getDx());
break;
case (KeyEvent.VK_RIGHT): Phil.setX(Phil.getX() + Phil.getDx());
break;
case (KeyEvent.VK_SPACE): Phil.setDy(Character.gravity * Character.dt);
Phil.setY(Phil.getY() + .5*Character.gravity*Character.dt*Character.dt + Phil.getDy()*Character.dt + Character.jump);
break;
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
Character class:
package test_game;
import java.awt.Color;
import java.awt.Graphics;
public class Character {
private int x;
private int y;
private int radius = 10;
Graphics g;
public static final int gravity = 15;
private static final double dx = 4;
public double dy;
public static final double dt = .2;
public static final int jump = 30;
public Character(int x, int y) {
this.x = x;
this.y = y;
}
public void setX(double d) {
this.x = (int) d;
}
public void setY(double d) {
this.y = (int) d;
}
public double getDx() {
return dx;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setDy(double dy) {
this.dy = dy;
}
public double getDy() {
return dy;
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillOval(x, y, radius, radius);
}
}
Upvotes: 0
Views: 268
Reputation: 18824
You have defined a KeyListener
inside you code. However, you forgot to register this event listener to a component, so its never called.
How to register your KeyListener:
Place the following code inside your start()
:
this.addKeyListener(this);
This fixes the problem with the character from moving to the left or right, however the jumping isn't fixed, fixing the jumping requires more code that calculates the correct y+ that you require, the current code always add 0 (rounded to 0 using the (int) you use) to the y coordinate when you press space.
Upvotes: 1