JFrame won't call paint method? - java

So I made Pong in a applet for a project in school but I realized that I can't hand in the project without creating an HTML file, so I'm attempting to change all my code from a applet to a JFrame. It all works, but my paint method isn't being called, any help will be great. Thanks for the help but to be honest im new to programming so if someone could make the changes to my code and then explain what you did, that would be great
package pong;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Main extends JPanel implements Runnable, KeyListener{//whatever class holds you main method
private static final long serialVersionUID = 1L;
int width = 600;
int height = width *9/16;
int Pwidth = 10, Pheight = 50, Px = 30, Py = height / 2-Pwidth, Pv = 3;
int Ewidth = 10, Eheight = 50, Ex = width - Ewidth - 30, Ey = height / 2-Ewidth - 50;
double Ev = 2.7;
int Bwidth = 10, Bheight = 10, Bx = width / 2 + 50, By = height / 2, Bvx = 3, Bvy = 3;
int TimeD = 0;
int Ms = 0, sec = 0, min = 0;
int Pscore = 0, Escore = 0, Pwinx = 800, Pwiny = height / 2, Ewinx = 800, Ewiny = height / 2;
boolean Bleft = true, Bright = false, Bup = true, Bdown = false;
boolean Pup = false, Pdown = false;
boolean Pa = false;
String string = new String();
public static JFrame frame;//public and static so other classes can access it. Might want to use a getter and setter here
public Main(){
frame=new JFrame("Pong, A game re-made by Camron Warren");// Create new JFrame
frame.setSize(width,height);//Set the size of the window
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);//Make sure all processes are closed when the window is closed
frame.setLocationRelativeTo(null);//Centers window
frame.setVisible(true);//Make the window visible
Thread th = new Thread(this);
addKeyListener(this);
th.start();
}
public static void main(String[] args){
new Main();//instantiate the Main class, this has to happen
}
#Override
public void run() {
while(true){
if(Pscore >= 5){
Pwinx = 100;
Py = height / 2 - Pheight / 2;
Bx = width / 2 - Bwidth;
By = height /2 - Bheight /2;
}
if(Escore >= 5){
Ewinx = 400;
Py = height / 2-Pwidth;
Bx = width / 2 - Bwidth;
By = height /2;
}
if(Escore >= 5 && Pa == true){
Pscore = 0;
Escore = 0;
Ewinx = 800;
Ms = 0;
sec = 0;
min = 0;
}
if(Pscore >= 5 && Pa == true){
Pscore = 0;
Escore = 0;
Pwinx = 800;
Ms = 0;
sec = 0;
min = 0;
}
//ball movement class
ballMovement();
//TIME COUNTER
Ms++;
if(Ms >= 60){
sec++;
Ms = 0;
}
if(sec >= 60){
min++;
sec = 0;
}
//BALLMOVEMENT
if(Bleft == true){
Bx-=Bvx;
}
if(Bright == true){
Bx+=Bvx;
}
if(Bup == true){
By-=Bvy;
}
if(Bdown == true){
By+=Bvy;
}
//BALLHITBOX
if(By <= 0){
Bup = false;
Bdown = true;
}
if(By + Bheight >= height){
Bdown = false;
Bup = true;
}
//SCORE SYSTEM
if(Bx <= 0){
Escore++;
Bx = width / 2 - Bwidth;
By = height / 2;
}
if(Bx+Bwidth >= width){
Pscore++;
Bx = width /2 - Bwidth;
By = height / 2;
}
//PHITBOX
if(Bx+Bwidth >= Px && Bx <= Px+Pwidth && By+Bheight >= Py && By <= Py+Pheight){
System.out.println("Phit");
Bleft = false;
Bright = true;
}
//EHITBOX
if(Bx+Bwidth >= Ex && Bx <= Ex + Ewidth && By+Bheight >= Ey && By <= Ey + Eheight){
System.out.println("Ehit");
Bright = false;
Bleft = true;
}
//PMOVEMENT
if(Pup == true){
Py-=Pv;
}
if(Pdown == true){
Py+=Pv;
}
//PHITBOX/APPLETHITBOX
if(Py <= 0){
Py = 0;
}
if(Py + Pheight >= height){
Py = height - Pheight;
}
//EHITBOX/APPLETHITBOX
if(Ey <= 0){
Ey = 0;
}
if(Ey + Eheight >= height){
Ey = height - Eheight;
}
//REPAINT
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
public void ballMovement()
{
if(By >= Ey)
{
Ey += Ev;
}
if(By <= Ey)
{
Ey -= Ev;
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_W){
Pup = true;
}
if(key == KeyEvent.VK_S){
Pdown = true;
}
if(key == KeyEvent.VK_UP){
Pup = true;
}
if(key == KeyEvent.VK_DOWN){
Pdown = true;
}
if(key == KeyEvent.VK_F1){
Pa = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_W){
Pup = false;
}
if(key == KeyEvent.VK_S){
Pdown = false;
}
if(key == KeyEvent.VK_UP){
Pup = false;
}
if(key == KeyEvent.VK_DOWN){
Pdown = false;
}
if(key == KeyEvent.VK_F1){
Pa = false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {}
#SuppressWarnings("deprecation")
public void update(Graphics g) {
Graphics offgc;
Image offscreen = null;
Dimension d = size();
offscreen = createImage(d.width, d.height);
offgc = offscreen.getGraphics();
offgc.setColor(getBackground());
offgc.fillRect(0, 0, d.width, d.height);
offgc.setColor(getForeground());
paint(offgc);
g.drawImage(offscreen, 0, 0, this);
}
#Override
public void paint(Graphics g){
g.setColor(Color.green);
g.fillRect(Px, Py, Pwidth, Pheight);
g.setColor(Color.RED);
g.fillRect(Ex, Ey, Ewidth, Eheight);
g.setColor(Color.BLACK);
g.fillOval(Bx, By, Bwidth, Bheight);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
g.drawString("Score: " + Pscore, 20, 20);
g.drawString("Score " + Escore , width - 60, 20);
g.drawString("Time played: " + min + ": " + sec, width / 2 - 50, 20);
g.setColor(Color.BLACK);
g.fillRect(width / 2, height, 1, height);
g.setColor(Color.BLACK);
g.drawLine(width / 2, 0, width / 2, height);
g.setColor(Color.BLACK);
g.drawString("Pong: a game re-made by Camron Warren", 10, height - 10);
g.drawString("Congrat's, you win!", Pwinx, Pwiny);
g.drawString("Press F1 to play again!", Pwinx, Pwiny + 10);
g.drawString("Enemy win's", Ewinx, Ewiny);
g.drawString("Press F1 to play again!", Ewinx, Ewiny + 10);
}
}

Related

How to fix this NullPointerException from my Platformer Game?

I am trying to make a Platformer game where you can run around and jump off the base of rectangles and off the sides of them.
I am compiling this in Processing 2.2.1. The program does not run. I am also looking for help on how to implement a jump and when to change the character's image.
speed = 0;
int numrects = 9;
Player player1 = new Player();
//Rectangle[] platforms = new Rectangle[16];
public static Rectangle[] platforms = new Rectangle[16];
class Player{
PImage[] images = new PImage[10];
int xMove, yMove, xSpeed, ySpeed, gravity, jumpheight, xSize, ySize;
boolean a = true;
boolean d = true;
boolean w = true;
int x, y;
int numFrames = 7; // The number of animation frames
int frame = 0; // The frame to display
PImage img;
Player (){
xSpeed = 10;
ySpeed = 10;
xSize = 24;
ySize = 51;
x = width/2;
y = height/2;
}
void jump() {
for (int x = 0; x <= jumpheight; x++){
y = y + gravity;
image(images[frame], x, y);
}
for (int x = 0; x <= jumpheight; x++){
y = y - gravity;
image(images[frame], x, y);
}
}
};
class Rectangle{
int x, y, xSize, ySize;
//.fill(127);
Rectangle(){
x = 1;
y = 1;
xSize = 10;
ySize = 10;
}
void build(int newx, int newy, int newxSize, int newySize){
x = newx;
y = newy;
xSize = newxSize;
ySize = newySize;
rect (x, y, xSize, ySize);
}
};
void setup() {
size(1920, 1080);
frameRate(30);
player1.images[0] = loadImage("Staticl.png");
player1.images[3] = loadImage("Staticr.png");
player1.images[1] = loadImage("step1left.png");
player1.images[4] = loadImage("step1right.png");
player1.images[2] = loadImage("step2left.png");
player1.images[5] = loadImage("step2right.png");
//images[3] = loadImage("1.jpg");
//images[7] = loadImage("2.jpg");
player1.xSpeed = 10;
player1.x = 500;
player1.y = 500;
platforms[0].build(0, 837, 1920, 244);
platforms[1].build(0, 765, 294, 23);
platforms[2].build(733, 725, 734, 39);
platforms[3].build(0, 765, 294, 23);
platforms[4].build(0, 765, 294, 23);
platforms[5].build(1306, 569, 161, 195);
platforms[6].build(558, 607, 653, 33);
platforms[7].build(0, 522, 496, 34);
platforms[8].build(477, 360, 173, 37);
platforms[9].build(690, 288, 445, 34);
platforms[10].build(1149, 174, 217, 40);
platforms[11].build(1390, 298, 243, 33);
platforms[12].build(1488, 490, 167, 30);
platforms[13].build(1690, 301, 138, 31);
platforms[14].build(1693, 426, 227, 27);
platforms[15].build(1866, 226, 54, 199);
}
void checkforcollision(){
for (int x = 0; x <= numrects; x++){
if (player1.x + player1.xSize == platforms[x].x && player1.y <= platforms[x].y + platforms[x].ySize && player1.y + player1.ySize >= platforms[x].y){
// right side of box hits left side of platform
player1.d = false;
player1.w = true;
}
else if(player1.x == platforms[x].x + platforms[x].xSize && player1.y <= platforms[x].y + platforms[x].ySize && player1.y + player1.ySize >= platforms[x].y){
// left side of box hits right side of platform
player1.a = false;
player1.w = true;
}
else if(player1.y + player1.ySize == platforms[x].y && player1.x <= platforms[x].x + platforms[x].xSize && player1.x + player1.xSize >= platforms[x].x){
// bottom of player hits top of box
player1.w = false;
}
else if(player1.y == platforms[x].y + platforms[x].ySize && player1.x <= platforms[x].x + platforms[x].xSize && player1.x + player1.xSize >= platforms[x].x){
// top of player hits bottom of box
player1.w = true;
player1.a = true;
player1.d = true;
}
else {
player1.w = false;
player1.a = true;
player1.d = true;
}
}
}
void draw() {
checkforcollision();
if (player1.d == true)
player1.x = player1.x + player1.xSpeed;
image(player1.images[player1.frame], player1.x, player1.y);
if (player1.a == true)
player1.x = player1.x - player1.xSpeed;
image(player1.images[player1.frame], player1.x, player1.y);
if (player1.w == true)
player1.jump();
//image(images[frame], player1.x, player1.y);
}
void keyPressed() {
if ((key == 'a') || (key == 'A')){
player1.a = true;
}
else if ((key == 'd') || (key == 'D')){
player1.d = true;
}
else if ((key == 'w') || (key == 'W')){
player1.w = true;
}
}
void keyReleased() {
if ((key == 'a') || (key == 'A')){
player1.a = false;
}
else if ((key == 'd') || (key == 'D')){
player1.d = false;
}
}
The NullPointerException is because you haven't initialized the Rectangles in the array yet. So this line causes an error:
platforms[0].build(0, 837, 1920, 244);
First, you need to run something like this:
for (int i=0; i<platforms.length; i++) {
platforms[i] = new Rectangle();
}

Why collision algorithm in my applet game does not work properly ?

This is my game project. It's very simple version of "Flappy Bird" and I have some serious problems with how the collisions algorithm works. I wrote 2 separate code fragments for collision, for wall1 and wall2. The problem begins when the ball is trying to go through a hole because somehow the program is detecting a collision with a wall. I'm almost positive that the collision algorithm was written correctly because I have been checking it all day.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends Applet implements KeyListener, Runnable {
Image bground;
Random generator = new Random();
int r1;
int wall1x;
int wall1y;
int wall1long;
int wall2x;
int wall2y;
int wall2long;
Timer timer;
private Image i;
private Graphics doubleG;
int r2;
int blok_x1 = 800;
int blok_y1;
int blok_x = 800;
int blok_y = 0;
int blok_x_v = 2;
int ballX = 20;
int ballY = 20;
int dx = 0;
int dyclimb = 1;
int dyrise = 1;
double gravity = 3;
double jumptime = 0;
int FPS = 100;
public int tab[];
public boolean grounded = true, up = false;
boolean OVER = false;
#Override
public void init() {
bground = getImage(getCodeBase(), "12.png");
this.setSize(600, 400);
tab = new int[100];
for (int t = 0; t < 100; t++) {
tab[t] = generator.nextInt(380) + 1;
}
addKeyListener(this);
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
ballX -= 10;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
ballX += 10;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
ballY -= 10;
up = true;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
ballY += 10;
}
}
#Override
public void paint(Graphics g) {
g.drawImage(bground, 0, 0, this);
if (OVER == false) {
for (int i = 0; i < 100; i++) {
g.setColor(Color.green);
wall1x = blok_x + i * 400;
wall1y = blok_y;
wall1long = tab[i];
g.fillRect(wall1x, wall1y, 20, wall1long);
g.setColor(Color.green);
wall2x = blok_x1 + i * 400;
wall2y = tab[i] + 60;
wall2long = 400 - tab[i];
g.fillRect(wall2x, wall2y, 20, wall2long);
g.setColor(Color.green);
}
g.setColor(Color.red);
g.fillOval(ballX, ballY, 20, 20);
} else {
g.drawString("GAME OVER", 300, 300);
}
}
#Override
public void update(Graphics g) {
if (i == null) {
g.setColor(Color.green);
i = createImage(this.getSize().width, this.getSize().height);
doubleG = i.getGraphics();
g.setColor(Color.green);
}
doubleG.setColor(getBackground());
g.setColor(Color.green);
doubleG.fillRect(0, 0, this.getSize().width, this.getSize().height);
doubleG.setColor(getForeground());
g.setColor(Color.green);
paint(doubleG);
g.drawImage(i, 0, 0, this);
}
#Override
public void run() {
int time = 10;
while (true) {
if (up == true) {
ballY -= dyclimb;
time--;
} else {
ballY += dyrise;
}
if (time == 0) {
time = 10;
up = false;
}
blok_x--;
blok_x1--;
if (ballX > 600 || ballX < 0 || ballY > 400 || ballY < 0) {
OVER = true;
}
for (int i = 0; i < 100; i++) { // collision algorithm
wall1x = blok_x + i * 400;
wall1y = blok_y;
wall1long = tab[i];
if (ballX + 20 >= wall1x && ballX <= wall1x + 20 && ballY <= wall1y + wall1long && ballY >= wall1x - 20) { //wall1
OVER = true;
}
}
for (int i = 0; i < 100; i++) {
wall2x = blok_x1 + i * 400;
wall2y = tab[i] + 60;
wall2long = 400 - tab[i];
if (ballX + 20 >= wall2x && ballX <= wall2x + 20 && ballY <= wall2y + wall2long && ballY >= wall2x - 20) { //wall2
OVER = true;
}
}
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException ex) {
Logger.getLogger(NewApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public void start() {
Thread thread = new Thread(this);
thread.start();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Use Rectangle class. There's a method called Intersect or Intersection or something like that.
Say you have one object moving. Make a Rectangle to match the object in position(basically an invisible cover for the object).
Do the same things with another object.
When both are to collide, use the intersection method to check on the collision by using the rectangles.
These might help
http://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html
Java method to find the rectangle that is the intersection of two rectangles using only left bottom point, width and height?
java.awt.Rectangle. intersection()

Why is my paint method only calling every other time?

I have a set of sprites that I am calling in a Java game, and when I had 3 sprites it worked fine, but when I add a fourth sprite, the repaint method is only called every other time.
Here is my minimal example,
Main class:
public class Maze extends JPanel implements ActionListener{
/**
* #param args
*/
int stage;
int dir;
int x = 32;
int y = 32;
Rectangle r = new Rectangle(x,y,10,10);
Draw D = new Draw();
public static ArrayList<Rectangle> walls = new ArrayList<Rectangle>();
public ArrayList<Image> spritesl = new ArrayList<Image>();
public ArrayList<Image> spritesd = new ArrayList<Image>();
public ArrayList<Image> spritesr = new ArrayList<Image>();
public ArrayList<Image> spritesu = new ArrayList<Image>();
BufferedImage image;
public Maze() throws IOException{
setBackground(Color.black);
setSize(672,672);
Timer timer = new Timer(2000,this);
timer.addActionListener(this);
timer.start();
//add sprites
for(int i = 1; i<5; i += 1){
spritesl.add(image = ImageIO.read(new File("C:/Users/Dave/Desktop/Sprites/left" + i + ".png")));
}
for(int i = 1; i<5; i += 1){
spritesd.add(image = ImageIO.read(new File("C:/Users/Dave/Desktop/Sprites/down" + i + ".png")));
}
for(int i = 1; i<5; i += 1){
spritesr.add(image = ImageIO.read(new File("C:/Users/Dave/Desktop/Sprites/right" + i + ".png")));
}
for(int i = 1; i<5; i += 1){
spritesu.add(image = ImageIO.read(new File("C:/Users/Dave/Desktop/Sprites/up" + i + ".png")));
}
}
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame();
Maze ate = new Maze();
frame.addKeyListener(new Input());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(ate);
frame.setPreferredSize(new Dimension(688, 709));//16, 37
frame.setVisible(true);
frame.pack();
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//call wall drawer
g.setColor(Color.gray);
D.draw(g);
g.setColor(Color.red);
//set animation
if(dir == 1){
g.drawImage(spritesu.get(stage-1),x,y, this);
}else if(dir == 2){
g.drawImage(spritesr.get(stage-1),x,y, this);
}else if(dir == 3){
g.drawImage(spritesd.get(stage-1),x,y, this);
}else if(dir == 4){
g.drawImage(spritesl.get(stage-1),x,y, this);
}
System.out.println("set");
}
#Override
public void actionPerformed(ActionEvent e) {
boolean up =false;
boolean right =false;
boolean down =false;
boolean left =false;
//next part tests each direction for collisions
if(Input.right){
right = true;
x += 4;
if(x>672-32){
x -= 4;
right = false;
}else{
for(int i = 0; i < walls.size(); i += 1){
if(new Rectangle(x, y, 30, 30).intersects(walls.get(i))){
x -= 4;
right = false;
}
}
}
}
if(Input.left){
left = true;
dir=4;
x-=4;
if(x<0){
x += 4;
left = false;
}else{
for(int i = 0; i < walls.size(); i += 1){
if(new Rectangle(x, y, 32, 32).intersects(walls.get(i))){
x += 4;
left = false;
}
}
}
}
if(Input.down){
down = true;
dir=3;
y+=4;
if(y>672-32){
y -= 4;
down = false;
}else{
for(int i = 0; i < walls.size(); i += 1){
if(new Rectangle(x, y, 32, 32).intersects(walls.get(i))){
y -= 4;
down = false;
}
}
}
}
if(Input.up){
up = true;
dir=1;
y-=4;
if(y<0){
y += 4;
up = false;
}else{
for(int i = 0; i < walls.size(); i += 1){
if(new Rectangle(x, y, 32, 32).intersects(walls.get(i))){
y += 4;
up = false;
}
}
}
}
//sets direction of animation
if(left||down||right||up){
if(left){
dir = 4;
}
if(down){
dir = 3;
}
if(right){
dir = 2;
}
if(up){
dir = 1;
}
stage += 1;
if(stage >= 4 || stage <= 0){
stage = 1;
}
System.out.println(stage);
}
repaint();
}
}
My input tester(probably not necessary, but its needed for the game to run):
public class Input implements KeyListener {
public static boolean left = false;
public static boolean right = false;
public static boolean up = false;
public static boolean down = false;
public static boolean space = false;
//test for keys
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
left = true;
if (key == KeyEvent.VK_RIGHT)
right = true;
if (key == KeyEvent.VK_UP)
up = true;
if (key == KeyEvent.VK_DOWN)
down = true;
if (key == KeyEvent.VK_SPACE)
space = true;
}
#Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
left = false;
if (key == KeyEvent.VK_RIGHT)
right = false;
if (key == KeyEvent.VK_UP)
up = false;
if (key == KeyEvent.VK_DOWN)
down = false;
if (key == KeyEvent.VK_SPACE)
space = false;
}
#Override
public void keyTyped(KeyEvent e) {}
}
and my Draw class:
public class Draw {
public void draw(Graphics g){
//draw everything
Maze.walls.clear();
g.fillRect(0, 0, 672, 32);
g.fillRect(0, 0, 32, 672);
g.fillRect(0, 640, 320, 32);
g.fillRect(352, 640, 320, 32);
g.fillRect(640, 0, 32, 320);
g.fillRect(640, 352, 32, 320);
Maze.walls.add(new Rectangle(0, 0, 672, 32));
Maze.walls.add(new Rectangle(0, 0, 32, 672));
Maze.walls.add(new Rectangle(0, 640, 320, 32));
Maze.walls.add(new Rectangle(352, 640, 320, 32));
Maze.walls.add(new Rectangle(640, 0, 32, 320));
Maze.walls.add(new Rectangle(640, 352, 32, 320));
}
}
now, this works and cycles three stages, but as soon as I change the stage max to 5, it only paints on stages 2 and 4, which are exactly the same. Can anyone tell me what I am doing wrong?
Swing "Timers coalesce events by default." As noted by #HOFE, re-reading your sprite images is likely slowing things down enough to trigger the effect. Instead, read the images into a List<Image> when the program starts.

java applet game jumping bug

I'm currently making a java game and I just managed to make the character jump but it only works half the time.
Sometimes he will jump perfectly but other times he will get stuck in the air. I think its something to do with the gravity variable changing but I'm not sure Please can you have a look?
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import java.util.TimerTask;
public class meatboy extends Applet implements KeyListener{
public int x = 10, y = 300, gravity = 3;
public int xs = 380, ys = 230 , jump_count, jump_move;
double jumptime = 0;
public boolean right, left, up, jump = true, start, grounded, grav = true;
public void init(){
setSize(800,400);
setBackground(Color.black);
addKeyListener(this);
/////Movement//////
Timer t = new Timer();
t.schedule(new TimerTask(){public void run(){
if (start == true){
if (right == true){
x = x + 3;
}if (left == true){
x = x - 3;
}if(up == true && jump == true){
jump_count++;
if (jump_count >= 100){
jump_count = 0;
}
if (jump_count >= 0 && jump_count <= 25){
//jump_move = 1;
y = y - 5;
}
if (jump_count >= 25 && jump_count <= 50){
//jump_move = 2;
y = y - 5;
}
if (jump_count >= 50 && jump_count <= 75){
//jump_move = 3;
y = y - 5;
}
if (jump_count >= 75 && jump_count <= 100){
//jump_move = 0;
y = y - 5;
jump = false;
}
}
/////GRAVITY//////
if (grav == true){y = y + gravity;}
///////Collision Dectection/////
if(x > 790){//right of screen stop
x = 10;
}if(x < 10){// left stop
x = 789;
}if(y > 350){
//y = y - 3;
grav = false;
jump = true;
}else{grav = true;}
////////////End of collision///////////
repaint();
}}},10,10);
///////movement end////////
}
public void paint(Graphics g){
////////CREATES MEATBOY///////////////
if (start == false){
x = 10;
y = 300;
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 800, 400);
g.setColor(Color.white);
g.drawString("MeatBoy 4K", 358, 180);
g.drawString("Press Z to start!!!!", 350, 200);
g.setColor(Color.RED);
g.fillRect(xs, ys, 16, 16);//meatboys body
g.fillRect(xs + 16, ys + 6, 4, 4);//arm
g.fillRect(xs - 4, ys + 6, 4, 4);//arm
g.fillRect(xs, ys + 12, 4, 6);//leg
g.fillRect(xs + 12, ys + 12, 4, 6);//leg
g.setColor(Color.black);
g.fillRect(xs + 2, ys + 2, 5, 5);//eye
g.fillRect(xs + 10, ys + 2, 5, 5);//eye
}
if (start == true){
g.setColor(Color.RED);
g.fillRect(x, y, 16, 16);//meatboys body
g.fillRect(x + 16, y + 6, 4, 4);//arm
g.fillRect(x - 4, y + 6, 4, 4);//arm
g.fillRect(x, y + 12, 4, 6);//leg
g.fillRect(x + 12, y + 12, 4, 6);//leg
g.setColor(Color.black);
g.fillRect(x + 2, y + 2, 5, 5);//eye
g.fillRect(x + 10, y + 2, 5, 5);//eye
///////////END OF MEATBOY//////////////////
////////Creates Floor///////////////////
g.setColor(Color.GRAY);
g.fillRect(0, 370, 800, 30);
}
}
/**
*
*/
private static final long serialVersionUID = 1L;
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_Z){
//right = true;
start = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
//right = true;
right = true;
}if (e.getKeyCode() == KeyEvent.VK_LEFT){
left = true;
}if (e.getKeyCode() == KeyEvent.VK_UP){
up = true;
}if (e.getKeyCode() == KeyEvent.VK_SPACE){
up = true;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
//right = true;
right = false;
}if (e.getKeyCode() == KeyEvent.VK_LEFT){
left = false;
}if (e.getKeyCode() == KeyEvent.VK_UP){
up = false;
}if (e.getKeyCode() == KeyEvent.VK_SPACE){
up = false;
}
}
public void keyTyped(KeyEvent e) {
}
}
Where does the player get stuck in the air?
If it's close to the ground, make sure that the y coordinate is right on the ground.
On this block of code:
}if(y > 350){
//y = y - 3;
grav = false;
jump = true;
}else{grav = true;}
Add
}if(y > 350){
//y = y - 3;
grav = false;
jump = true;
//I'm on the ground all right
y = 350;
}else{grav = true;}

AffineTransform mouse aiming rotation stutter on 90 degrees

EDIT:
OH!!!!!
it works!!!
It seems that at one point it was fixed However the wrong HTML file was opening up so the wrong code was running. I feel stupid, that should have been obvious.
But THANKYOU!!!
Its so awesome to actually get some help with this stuff. whenever i ask for some help anywhere else or even ask my teacher im usually ignored or get useless advice.
(end of edit)
Im making a game for my final project in a java class. I just got mouse aiming to work using AffineTransform, however When ever the player object rotates to 90 degrees(or a multiple of it), it does this weird stutter thing.
Heres the code im specifically concerned with.
g2.drawImage(img, x_pos,y_pos,this);
AffineTransform oldTransform = g2.getTransform();
g2.setTransform(AffineTransform.getRotateInstance(radAngle,x_pos + (img.getWidth() / 2),y_pos+(img.getHeight() / 2)));
Could someone please help me figure out how to fix this? my project is due tomorrow so im slim on time.
Here are the images i use
Heres the code.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.lang.Math.*;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.imageio.ImageIO;
import java.io.*;
import java.net.URL;
public class Game extends Applet implements Runnable, KeyListener, MouseMotionListener
{
int x_pos = 250;
int y_pos = 250;
float x_speed = 0;
float y_speed = 0;
int radius = 20;
int appletsize_x = 800;
int appletsize_y = 600;
int x = 0;
int y = 0;
int up = 0;
int down= 0;
int left = 0;
int right= 0;
int mouse_x;
int mouse_y;
int tracking_angle;
private BufferedImage dbImage;
private Graphics dbg;
private Image curser;
BufferedImage img = null;
BufferedImage round = null;
AffineTransform at = new AffineTransform();
double radAngle;
public void init()
{
try {
URL url = new URL(getCodeBase(), "Player.png");
img = ImageIO.read(url);
} catch (IOException e) {System.out.println("Cant find player image");
}
try {
URL url = new URL(getCodeBase(), "round.png");
round = ImageIO.read(url);}
catch (IOException e) {}
setBackground (Color.blue);
setFocusable(true);
addKeyListener( this );
curser = getImage(getDocumentBase(), "mouse.png");
addMouseMotionListener(this);
try
{
Toolkit tk = Toolkit.getDefaultToolkit();
Cursor c = tk.createCustomCursor( curser,new Point( 5, 5 ), "Inodrop" );
setCursor( c );
}
catch( IndexOutOfBoundsException x )
{}
}
public class Shot {
int x_loc = -50;
int y_loc = -50;
public Shot(){
if(x_loc < 0){
x_loc = x_pos;}
if(y_loc < 0){
y_loc = y_pos;}
paint(dbg);}
public void paint(Graphics g){
System.out.println("hi");
Graphics2D g2d = (Graphics2D)g;
Graphics g2D = round.getGraphics();
g2d.drawImage(round, x_loc,y_loc,null);}}
public void start ()
{
Thread th = new Thread (this);
th.start ();
}
public void stop()
{
}
public void destroy()
{
}
public void mouseMoved(MouseEvent e){
//get position of mouse
mouse_x = e.getX();
mouse_y = e.getY();
double x_dist = mouse_x - x_pos;
double y_dist = mouse_y - y_pos;
if (x_dist == 0) {
radAngle = 90;
} else if ((x_dist == 0) && (y_dist == 0)) {
radAngle = 0;
} else {
radAngle = Math.atan(y_dist / x_dist);
}
tracking_angle = (int)(Math.sin(radAngle) * 100);
//System.out.println(Math.toRadians(tracking_angle));
}
public void mouseDragged(MouseEvent e){}
public void keyReleased(KeyEvent r)
{
//Left
if (r.getKeyCode() == 39 ){
x = 0;
left = 0;
Shot shoot = new Shot();
}
//Right
if (r.getKeyCode() == 37){
x = 0;
right = 0;
}
//Down
if (r.getKeyCode() == 38 ) {
//y_speed = 0;
down = 0;}
//Up
if (r.getKeyCode() == 40 ) {
//y_speed = 0;
up = 0;}
//move();
}
public void keyTyped(KeyEvent t){}
public void keyPressed(KeyEvent r){
//Left
if (r.getKeyCode() == 39 ){
left = 1;}
//Right
if (r.getKeyCode() == 37){
right = 1;}
//Down
if (r.getKeyCode() == 38 ) {
down = 1;}
//Up
if (r.getKeyCode() == 40 ) {
up = 1;}
//move();
}
public void run ()
{
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true)
{
if (left == 1 && x_speed < 11){
x = 0;
x_speed += 1;
}
//Right
if (right == 1 && x_speed > -11){
x = 0;
x_speed -= 1;
}
//Down
if (down == 1 && y_speed > -11) {
y_speed -= 1;}
//Up
if (up == 1 && y_speed < 11) {
y_speed += 1;}
if( x == 0 && x_speed > 0){
x_speed -=.2;}
if( x == 0 && x_speed < 0){
x_speed +=.2;}
if( y == 0 && y_speed > 0){
y_speed -=.2;}
if( y == 0 && y_speed < 0){
y_speed +=.2;}
if (x_pos > appletsize_x - radius && x_speed > 0)
{
x_pos = radius;
}
else if (x_pos < radius && x_speed < 0)
{
x_pos = appletsize_x + radius ;
}
//System.out.println(y_pos);
if (y_pos > appletsize_y - radius && y_speed > 0){
y_speed = 0;}
else if ( y_pos < radius && y_speed < 0 ){
y_speed = 0;}
x_pos += (int)x_speed;
y_pos += (int)y_speed;
repaint();
try
{
Thread.sleep (15);
}
catch (InterruptedException ex)
{
}
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}
public void update (Graphics g)
{
if (dbImage == null)
{
dbImage = new BufferedImage(this.getSize().width, this.getSize().height, BufferedImage.TYPE_INT_RGB);
dbg = dbImage.getGraphics ();
}
dbg.setColor (getBackground ());
dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
dbg.setColor (getForeground());
paint (dbg);
g.drawImage (dbImage, 0, 0, this);
}
public void paint (Graphics g)
{
//g = img.getGraphics();
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(img, x_pos,y_pos,this);
AffineTransform oldTransform = g2.getTransform();
g2.setTransform(AffineTransform.getRotateInstance(radAngle,x_pos + (img.getWidth() / 2),y_pos+(img.getHeight() / 2)));
System.out.println(img.getWidth());
}
}
double x_dist = mouse_x - x_pos;
double y_dist = mouse_y - y_pos;
double radAngle = Math.atan(y_dist / x_dist);
tracking_angle = (int) (Math.sin(radAngle) * 100);
I think the error is somewhere in this part. You're definitely dividing by 0 here if x_dist is 0. Better do something like this:
if (x_dist == 0) {
radAngle = 90;
} else {
radAngle = Math.atan(y_dist / x_dist);
}
EDIT: Additionally, I think you should throw away the tracking_angle line completely and just do this later:
g2.setTransform(AffineTransform.getRotateInstance(rad_angle,
x_pos + (img.getWidth() / 2),y_pos+(img.getHeight() / 2)));
Also you should change that new code you posted in the comments:
double radAngle;
if (x_dist == 0) {
radAngle = 90;
} else if (y_dist == 0) {
radAngle = 90;
} else {
radAngle = Math.atan(y_dist / x_dist);
}
You are solving this for x_dist == 0 or y_dist == 0 (which isn't an edge case), but not for the case that both are 0 where you simply can't compute an angle and I think you should go with 0. So use this instead:
double radAngle;
if (x_dist == 0) {
radAngle = 90;
} else if ((x_dist == 0) && (y_dist == 0)) {
radAngle = 0;
} else {
radAngle = Math.atan(y_dist / x_dist);
}
Also, as trashgod pointed out, you're ignoring exceptions, for example:
try {
URL url = new URL(getCodeBase(), "Player.png");
img = ImageIO.read(url);
} catch (IOException e) {
}
You should not just continue in such cases but f.e. display an useful error message and quit the program, in any case do something instead of just catching the exception and continue as if nothing happened.
I haven't tested this, but try:
double radAngle = Math.atan2(y_dist, x_dist);

Categories

Resources