Bullet not travelling up! Java game - java

I'm a newbie in Java and I'm trying to make a ship fire a bullet. What I want is actually make the ship fire bullets as long as the Spacebar button is being held down.
I've successfully made the ship move here and there and also fire the bullet. However the bullet just won't go up. Here's my code -
package learningPackage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Draw extends JFrame implements Runnable {
//Variables for the x and y coordinates, xDirection for modifying the values of x only.
int x, y, xDirection;
int bx, by;
Image dbImage;
Graphics dbGraphics;
boolean shot;
Rectangle bullet;
//Thread run
public void run() {
try {
while (true) {
move();
shoot();
//Setting sleep to 0 will make it light-speed!
Thread.sleep(5);
}
}
catch (Exception e) {
System.out.println("Error!");
}
}
//Ship move
//Ship moves only in one direction, x - axis
public void move() {
x += xDirection;
//Collision detection
if (x <= 10) {
x = 10;
}
if (x >= 415) {
x = 415;
}
}
//KeyListeners
public class AL extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == e.VK_LEFT) {
xDirection = -2;
}
if (keyCode == e.VK_RIGHT) {
xDirection = 2;
}
if (keyCode == e.VK_SPACE) {
shot = true;
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == e.VK_LEFT) {
xDirection = 0;
}
if (keyCode == e.VK_RIGHT) {
xDirection = 0;
}
if (keyCode == e.VK_SPACE) {
shot = false;
}
}
}
//Constructor for the game frame
public Draw() {
super("Game");
setSize(500, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
addKeyListener(new AL());
x = 200;
y = 465;
setVisible(true);
}
//Double - buffering
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbGraphics = dbImage.getGraphics();
paintComponent(dbGraphics);
g.drawImage(dbImage, 0, 0, this);
}
//All the graphics
public void paintComponent(Graphics g) {
bullet = new Rectangle(bx, by, 10, 10);
g.setColor(Color.RED);
//Ship rectangle
g.fillRect(x, y, 75, 25);
//Gun rectangle
g.fillRect(x + 32, y - 15, 10, 15);
//Setting the same values for bx and by as x and y so that the bullet will start from the Gun rectangle
bx = x + 32;
by = y - 15;
if (shot == true) {
g.setColor(Color.BLACK);
g.fillRect(bx, by, bullet.width, bullet.height);
}
repaint();
}
public void shoot() {
if (shot == true) {
by = by - 2;
}
if (by <= -5) {
//Resetting values
bx = x + 32;
by = y - 15;
bullet = new Rectangle(bx, by, 10, 10);
shot = false;
}
}
//Main method
public static void main(String[] args) {
Draw gameTry = new Draw();
Thread t1 = new Thread(gameTry);
t1.start();
}
}
Here's what happens when I just move the ship, working perfectly fine -
Here's what happens when I hold down space -
(Sorry for not being able to embed pics in the post itself, I'm new to Stack Overflow as well!)
I was actually coping this code from a tutorial but since the tutorial-code wasn't working out, I decided to do this on my own, but I can't do it on my own as well!
Help will definitely be appreciated!

The reason for the bullet not moving becomes appearant when you compare your shoot() method, and the paintComponent method.
Shoot checks if you have the shot boolean set, and if so, moves the bullet y position up by 2.
When the bullet leaves the top of the screen, it resets the "bullet".
This is all fine, it does what it's supposed to.
public void shoot() {
if (shot == true) {
by = by - 2; //this is fine, it moves the bullet up
}
if (by <= -5) {
//Resetting values
bx = x + 32;
by = y - 15;
bullet = new Rectangle(bx, by, 10, 10);
shot = false;
}
}
Then comes paintComponent, which is executed time your game is "painted" to the screen.
It defines a rectangle for the bullet at its current position,
draws the ship,
Then overwrites the bullet's x and y position so it sits on top of the ship.
That is where your problem is
public void paintComponent(Graphics g) {
bullet = new Rectangle(bx, by, 10, 10);
g.setColor(Color.RED);
g.fillRect(x, y, 75, 25);
g.fillRect(x + 32, y - 15, 10, 15);
//you are messing with bx and by here.
//probably because you wanted the bullet to be in the
//same position as the ship.
//this means they will be put back into the same position
//for every time your game is painted to the screen.
//my advice is, do *not* do this here.
bx = x + 32;
by = y - 15;
if (shot == true) {
g.setColor(Color.BLACK);
g.fillRect(bx, by, bullet.width, bullet.height);
}
repaint();
}

Related

Trying to move two objects at the same time with arrow keys and WASD

Hey guys I am making a game in which characters can be moved with WASD and Arrow keys. I got them to move but i can not make them move at the same time. One can not be moving for the other shape to move. Is there a way to check for WASD and arrow presses simultaneously? Hope you guys can help. Thanks in advance.
Here is the code:
// The "SoccerGame" class.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class SoccerGame extends Applet implements KeyListener
{
//x and y values of the player 1 and 2's character and the ball
int x1 = 0, y1 = 275, x2 = 780, y2 = 275, xBall = 400, yBall = 275;
public void init ()
{
this.requestFocus ();
addKeyListener (this);
//setting size of program
setSize (800, 550);
} // init method
public void paint (Graphics g)
{
//Player 1
g.setColor (Color.red);
g.fillRect (x1, y1, 30, 30);
//Player2
g.setColor (Color.black);
g.fillRect (x2, y2, 30, 30);
//Ball
g.setColor (Color.blue);
g.fillRect (xBall, yBall, 30, 30);
} // paint method
public void keyPressed (KeyEvent e)
{
//Moving Player 1 with arrow Keys
if (e.getKeyCode () == e.VK_W)
{
y1 = y1 - 10;
}
if (e.getKeyCode () == e.VK_S)
{
y1 = y1 + 10;
}
if (e.getKeyCode () == e.VK_A)
{
x1 = x1 - 10;
}
if (e.getKeyCode () == e.VK_D)
{
x1 = x1 + 10;
}
//Moving player 2 with WASD
if (e.getKeyCode () == e.VK_UP)
{
y2 = y2 - 10;
}
if (e.getKeyCode () == e.VK_DOWN)
{
y2 = y2 + 10;
}
if (e.getKeyCode () == e.VK_LEFT)
{
x2 = x2 - 10;
}
if (e.getKeyCode () == e.VK_RIGHT)
{
x2 = x2 + 10;
}
repaint ();
}
public void keyReleased (KeyEvent e)
{
}
public void keyTyped (KeyEvent e)
{
}
} // SoccerGame class
Don't use a KeyListener (as you have been suggested in your other questions).
Instead you should be using Key Bindings. You will then need to track which keys have been pressed and use a Swing Timer to schedule the animation.
Check out Motion Using the Keyboard.
The KeyboardAnimation.java example shows how this can be done.

Processing 3.06b merging programs

i have been working on some code and merging two programs I have created but I understand I am missing a lot of information as I have many errors but I can't seem to fix the error. Below I have included the whole code which has been separated into classes. I am producing a version of space invaders.
Main class:
Bullets [] bullets = new Bullets[10];
Player player = new Player();
Boolean keyLftPressed = false, keyRghtPressed = false;
//Enemies[] enemies = new Enemies();
int state;
String gameLevel = "Main menu";
Boolean startTime = false;
void setup() {
for(int i=0; i<bullets.length; i++)
{
// if(i%2==0)
// bullets[i] = new Bullets();
// else
// bullets[i] = new Bullets(i);
}
size(800, 600);
state = 0;
}
void draw() {
background(255);
gameState();
player1.display();
movePlayer1();
handleEnemies();
handleBullets();
gamewon();
}
void gameState() {
if (gameLevel == "Main menu") {
background(0);
fill(255, 255, 255);
rect(270, 270, 280, 50, 20, 20, 20, 20);
//Draws rectangle for play game
fill(0);
textSize(30);
text("Play Game", 330, 305);
fill(255, 0, 0);
textSize(50);
text("Space Invaders", 220, 120);
if (mousePressed && mouseX > 250 && mouseX < 250 + 280 && mouseY > 270 && mouseY < 270 + 50)
{
gameLevel = "Level 1";
}
} else if (gameLevel == "Level 1")
{
background (255, 2555 , 255);
}
}
Bullets Class:
class Bullets {
class Bullet {
float x, y;
float velocity;
Bullet(float x, float y, float velocity) {
this.x = x;
this.y = y;
this.velocity = velocity;
}
void display(){
fill(80);
rect(this.x, this.y, 5,15);
}
void move(){
this.y+=this.velocity;
if (this.y > height || this.y < 0){
bullets.remove(this);
}
}
Class Enemies:
class Enemies {
float x, y;
float velocity;
Enemy(float x, float y) {
this.x = x;
this.y = y;
this.velocity = 3;
}
void display() {
fill(0,255,0);
ellipse(this.x, this.y, 30, 30);
noFill();
}
void move() {
this.x+=this.velocity;
if (this.x > width*.9) {
this.x = width*.9;
this.velocity *= -1;
this.y+=30;
}
if (this.x < width*.1) {
this.velocity*=-1;
this.x = width*.1;
this.y+=30;
}
}
void hitCheck() {
for (int i = 0; i < bullets.size(); i++){
Bullet b = (Bullet) bullets.get(i);
float distBetween = dist(b.x, b.y, this.x, this.y);
if (distBetween < 15 && b.velocity < 0){
score++;
enemies.remove(this);
float x = width*.1 + i%numCol*50;
float y = 60 + int(i/numCol)*60 ;
enemies.add(new Enemy(x, y));
}
}
}
}
Class Player:
class Player {
void movePlayer1() {
if (keyLftPressed) {
player1.x -=10;
}
if (keyRghtPressed) {
player1.x +=10;
}
}
void keyPressed() {
if (keyCode == LEFT) {
keyLftPressed = true;
}
else {
if (keyCode == RIGHT) {
keyRghtPressed = true;
}
else {
if (key == 'f') {
player1.shoot();
}
}
}
}
void keyReleased() {
if (keyCode == LEFT) {
keyLftPressed = false;
}
else {
if (keyCode == RIGHT) {
keyRghtPressed = false;
}
}
}
Class Score:
void gameFinish() {
{
for (int i = 0; i < 3; i++)
{
fill(color(255,0,0));
fill(255, 0, 0);
textAlign(CENTER);
text("Game over", width/2, height/2 - 50);
text(" Final score : "+ score, width/2, height/2 + 50);
}
}
}
}
void gamewon()
{
if (score == 10)
{
background(0);
fill(color(255,0,0));
fill(255, 0, 0);
textAlign(CENTER);
text("Congratulations you won!", width/2, height/5);
text(" Your final score is : "+ score, width/2, height/5 + 30);
text("Do you wish to continue?",width/2, height/2);
text(" If so press Y to Continue or N to exit ", width/2, height/2+30);
noLoop();
}
}
I don't want to be disheartening, but this code is a mess. You've got a ton of errors here, and asking us to go through all of them is asking quite a bit.
That being said, I'll try to get you started in the right direction.
First of all, you're missing closing curly brackets on several of these classes. Proper indenting will help you narrow this down, or you could consider putting each class in its own tab.
Then in your Player class, you use a variable named player1. Where is that variable defined? Do you mean to use the player variable? For that matter, since you're in the Player class already, why are you referring to a variable at all? Shouldn't you just use the x variables in that instance directly?
Which brings us to the next problem: your Player class doesn't actually define an x variable!
Similarly, your Player class calls a shoot() function, which doesn't seem to exist. You have to define that function.
Then let's see here... your Score class uses a score variable that doesn't seem to be declared anywhere.
Also, your bullets variable is an array, but you're calling functions on it that only work on an ArrayList object. Pick one or the other.
You also call a bunch of functions that don't exist: movePlayer1(), handleEnemies(), handleBullets(), and gameWon() for example. Some of these functions are defined inside of classes, so you need to use an instance of that class to get to the functions. Like this:
Example e = new Example();
e.function();
class Example{
void function(){
println("here");
}
}
Then your Enemies class has a constructor of Enemy, which isn't valid. Choose one or the other.
You're not going to like hearing this, but honestly, your best bet is probably to start from scratch. I would guess that you're trying to copy-paste all of this code from different sources without really understanding what the code is doing, which is a horrible idea. That never works, even for experienced programmers.
Instead, try breaking your problem down into smaller pieces. Get a single rectangle on the screen, then make it move around when you press the arrow keys, then add the ability to shoot. Then try adding some enemies, but only after the previous steps work perfectly!
If you get stuck, post an MCVE that shows the small step you're stuck on- not your entire project!

How do I remove the red rectangle when it collides with the cyan one?

This is my code:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class Draw extends JComponent implements KeyListener {
Random r = new Random();
int x = 0;
int y = 0;
int a = 5 * r.nextInt(150);
int b = 5 * r.nextInt(90);
Image img1 = Toolkit.getDefaultToolkit().getImage("C:/Users/Administrator/eclipse/My Projects/Game/src/bluebackground1.png");
public Draw(){
addKeyListener(this);
setFocusable(true);
}
//display
public void paint(Graphics g){
g.drawImage(img1, 0, 0, this);
g.setColor(Color.CYAN);
g.fill3DRect(x, y, 50, 50, true);
g.setColor(Color.RED);
g.draw3DRect(a, b, 50, 50, true);
g.setColor(Color.BLACK);
g.drawLine(0, 500, 800, 500);
g.setColor(Color.BLACK);
g.drawString("Press R to restart the game", 10, 540);
g.drawString("Use arrow keys to move", 600, 540);
if(x == a && y == b){
g.setColor(Color.BLACK);
g.setFont(new Font("", Font.PLAIN, 50));
g.drawString("Victory", 300, 550);
}
}
//controls
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_UP){
y -= 5;
} else if(k.getKeyCode() == KeyEvent.VK_DOWN){
y += 5;
} else if(k.getKeyCode() == KeyEvent.VK_LEFT){
x -= 5;
} else if(k.getKeyCode() == KeyEvent.VK_RIGHT){
x += 5;
}
if(k.getKeyCode() == KeyEvent.VK_R){
restart();
}
//border
if(x < 0){
x += 5;
} else if(x > 745){
x -= 5;
} else if(y < 0){
y += 5;
} else if (y > 450){
y -= 5;
}
repaint();
}
public void keyReleased(KeyEvent k) {}
public void keyTyped(KeyEvent k) {}
//restart function
public void restart(){
x = 0;
y = 0;
a = 5 * r.nextInt(150);
b = 5 * r.nextInt(90);
}
}
What I want is when the cyan rectangle which is moveable gets inside the red rectangle which is not moveable the red rectangle disappears permanently because the game is not over and the cyan rectangle will have to move more.
How do I remove the red rectangle when it collides with the cyan one?
Store Shape instances in a List. At time of painting, iterate the list and draw each one. When one shape is removed, remove it from the list and call repaint().

I cannot get my collision to work in Java

I want to know how I can make collision happen between the two circles. One of them is movable, as you can see, and I want to make it so that the movable circle can actually push the smaller one. However, I don't want simple rectangle collision. I'm trying to make it so that the circles direction of push depends on the positions of the two circles.
package haex;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class haex extends Applet implements Runnable, KeyListener{
private static final long serialVersionUID = 1L;
int x = 0, y = 0, footballX = 100, footballY = 100;
double angle, xVel, yVel;
Image dbImage;
Graphics dbg;
boolean up, down, left, right, kick;
public void init(){
addKeyListener(this);
}
public void start(){
Thread th = new Thread(this);
th.start();
}
public void run(){
while(true){
angle = Math.atan2((footballX + 12) - (x + 25), (footballY + 12) - (y + 25));
if(Math.sqrt(Math.pow((footballX + 12) - (x + 25), 2) + Math.pow((footballY + 12) - (y + 25), 2)) <= 37){
xVel = Math.cos(angle);
yVel = Math.sin(angle);
footballX += xVel;
footballY += yVel;
}
if(up) y--;
if(down) y++;
if(left) x--;
if(right) x++;
try{Thread.sleep(1000/60);}catch(InterruptedException x){}
repaint();
}
}
public void stop(){}
public void destroy(){}
public void paint(Graphics g){
if(kick){
g.setColor(Color.lightGray);
}else{
g.setColor(Color.black);
}
g.fillOval(x, y, 50, 50);
g.setColor(Color.blue);
g.fillOval(x + 5, y + 5, 40, 40);
g.setColor(Color.black);
g.fillOval(footballX, footballY, 24, 24);
g.setColor(Color.white);
g.fillOval(footballX + 2, footballY + 2, 20, 20);
g.setColor(Color.black);
g.drawLine(x + 25, y + 25, footballX + 12, footballY + 12);
}
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_UP) up = true;
if(e.getKeyCode() == KeyEvent.VK_DOWN) down = true;
if(e.getKeyCode() == KeyEvent.VK_LEFT) left = true;
if(e.getKeyCode() == KeyEvent.VK_RIGHT) right = true;
if(e.getKeyCode() == KeyEvent.VK_X) kick = true;
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_UP) up = false;
if(e.getKeyCode() == KeyEvent.VK_DOWN) down = false;
if(e.getKeyCode() == KeyEvent.VK_LEFT) left = false;
if(e.getKeyCode() == KeyEvent.VK_RIGHT) right = false;
if(e.getKeyCode() == KeyEvent.VK_X) kick = false;
}
public void update(Graphics g){
if(dbImage == null){
dbImage = createImage(this.getSize().width, this.getSize().height);
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);
}
#Override
public void keyTyped(KeyEvent e){}
}
Doing circular collision should be even easier than rectangular, just use a single radius for each instead of seperate x and y dimensions. Just calculate if the distance between their center points is less than the radius of both. If so, they're touching, if not, they aren't.
EDIT:
So the problem is calculating the resultant velocities and directions of the balls AFTER collision, not calculating the collision itself? Learn to explain the problem accurately if you want accurate help.
In that case, compare the X values of the two center points and the Y values of the two center points. Collisions should be largely elastic, so if a ball is hit on the left side, it should go to the right side, and vise versa. Then you just have to combine the X and Y components into a vector to get the direction and magnitude of the reaction.

How come this AffineTransform rotation method works?

Ive been programming a game just to become better at java. I had been having alot of trouble with getting the player rotation to work correctly. My first method used this
g2.setTransform(AffineTransform.getRotateInstance(radAngle,x_pos + (img.getWidth() / 2),y_pos+(img.getHeight() / 2)));
However this caused all images to rotate with the player thus making shooting and aiming completely disfunctional.
i was researching and saw someone use this code to make they're player rotate.
Graphics2D g2 = (Graphics2D)g;
AffineTransform oldTransform = g2.getTransform();
AffineTransform newOne = (AffineTransform)(oldTransform.clone());
newOne.rotate(radAngle,x_pos + (img.getWidth() / 2),y_pos+ (img.getHeight() / 2));
g2.setTransform(newOne);
g2.drawImage(img, x_pos,y_pos,this);
repaint();
g2.setTransform(oldTransform);
This works great and i dont have the same problems i had before. However i dont know why.
Heres my full code. The code above is for the body of the paint method.
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;
import java.util.ArrayList;
public class Game extends Applet implements Runnable, KeyListener, MouseMotionListener, MouseListener
{
//pos variables keep track of the current position of the player
int x_pos = 250;
int y_pos = 250;
//speed variables keep track of the speed/how many pixels will be added to position during this iteration of the thread
float x_speed = 0;
float y_speed = 0;
int radius = 25;
//denotes the boundries of the applet
int appletsize_x = 800;
int appletsize_y = 600;
//the x and y variables mark whether a movement key is being pressed thats telling the object to move on
//on of those axes's
int x = 0;
int y = 0;
//variables that will indicate whether one of those keys are being depressed
int up = 0;
int down= 0;
int left = 0;
int right= 0;
int mouse_x;
int mouse_y;
int tracking_angle;
//getting some images.
private BufferedImage dbImage;
private BufferedImage test;
private Graphics dbg;
private Image curser;
BufferedImage img = null;
BufferedImage round = null;
double x_dist;
double y_dist;
//i dont use this AffineTransform, although ill leave it here just incase i decide to use it if i continue working
//on this independently.
AffineTransform at = new AffineTransform();
//the angle of the mouse to the player object.
double radAngle;
public void init()
{
try {
URL url = new URL(getCodeBase(), "UFO.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) {System.out.println("round not loading");}
setBackground (Color.black);
setFocusable(true);
addKeyListener( this );
curser = getImage(getDocumentBase(), "mouse.png");
addMouseMotionListener(this);
addMouseListener(this);
try
//changing the curser to the crosshair image
{
Toolkit tk = Toolkit.getDefaultToolkit();
Cursor c = tk.createCustomCursor( curser,new Point( 5, 5 ), "Cross_Hair" );
setCursor( c );
}
catch( IndexOutOfBoundsException x )
{System.out.println("Cross_hair");}
}
public class Shot {
final double angle = radAngle;
double x_loc;
double y_loc;
double X;
double Y;
public Shot(){
x_loc += x_pos;
y_loc += y_pos;
X=Math.cos(radAngle)*5;
Y=Math.sin(radAngle)*5;
}
public void move(){
x_loc += X;
y_loc += Y;}
}
//start the thread
public void start ()
{
Thread th = new Thread (this);
th.start ();
}
public void stop()
{
}
public void destroy()
{
}
//cathces the mouseEvent when the mosue is moved.
public void mouseClicked(MouseEvent e){}
public void mousePressed(MouseEvent e){
Shot shoot = new Shot();
shots.add(shoot);}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseMoved(MouseEvent e){
//get position of mouse
mouse_x = e.getX();
mouse_y = e.getY();
//get the distence from the player to the
//i calculate the actual angle of the mosue from the player object in radians
//this exists more just for debugging purposes since radians make no sense to me
tracking_angle = 90;
}
public void mouseDragged(MouseEvent e){
mouse_x = e.getX();
mouse_y = e.getY();
Shot shoot = new Shot();
shots.add(shoot);}
//this method sets the key variables to zero when the keys are released
public void keyReleased(KeyEvent r)
{
//Right
if (r.getKeyCode() == 68 ){
x = 0;
left = 0;
}
//Left
if (r.getKeyCode() == 65){
x = 0;
right = 0;
}
//Up
if (r.getKeyCode() == 87 ) {
//y_speed = 0;
down = 0;}
//Down
if (r.getKeyCode() == 83 ) {
//y_speed = 0;
up = 0;}
//move();
}
public void keyTyped(KeyEvent t){}
//changes the variables when a key is pressed so that the player object will move
public void keyPressed(KeyEvent r){
//right
if (r.getKeyCode() == 68 ){
left = 1;
}
//left
if (r.getKeyCode() == 65){
right = 1;}
//Down
if (r.getKeyCode() == 87 ) {
down = 1;}
//Up
if (r.getKeyCode() == 83) {
up = 1;}
//move();
}
//sorta like the body of the thread i think
public void run ()
{
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true)
{
System.out.println(Math.tan(radAngle)/1);
x_dist = mouse_x - x_pos;
y_dist = mouse_y - y_pos;
radAngle = Math.atan2(y_dist , x_dist);
//if(tracking_angle < 0){
//tracking_angle = absT
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 ;
}
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
{
//tells the thread to wait 15 milliseconds util it executes again.
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);
shot_draw(dbg);
g.drawImage (dbImage, 0, 0, this);
}
ArrayList<Shot> shots = new ArrayList<Shot>();
double last_angle = 1000;
public void paint (Graphics g){
Graphics2D g2 = (Graphics2D)g;
AffineTransform oldTransform = g2.getTransform();
AffineTransform newOne = (AffineTransform)(oldTransform.clone());
newOne.rotate(radAngle,x_pos + (img.getWidth() / 2),y_pos+(img.getHeight() / 2));
g2.setTransform(newOne);
g2.drawImage(img, x_pos,y_pos,this);
repaint();
g2.setTransform(oldTransform);
// g2.setTransform(AffineTransform.getRotateInstance(radAngle,x_pos + (img.getWidth() / 2),y_pos+(img.getHeight() / 2)));
//g2.getTransform().setToIdentity();
}
public void shot_draw(Graphics g){
Graphics2D g2 = (Graphics2D)g;
// Shot shoot = new Shot();
// shots.add(shoot);
for(Shot i: shots){
g2.drawImage(round,(int)i.x_loc+40,(int)i.y_loc+40,this);
i.move();}
}}
Here are the images I'm using:
This makes sense since if you don't reset the Graphics object's AffineTransform back to its baseline, it will use the new transform to draw everything including all images. I don't understand however why you have a call to repaint() from within your paint method. You shouldn't do this.
The AffineTransform object is connected to the Graphics2D object via the call to setTransform. Once connected, the transform causes every object drawn using the Graphics2D object to be drawn with that same transform (in this case, rotation) applied to it until a new AffineTransform is assigned to the Graphics2D object via another call to setTransform. The sample code you found saved the old transform (which presumably encodes a normal, non-rotated state) via
AffineTransform oldTransform = g2.getTransform();
The code then created the rotation transform and connected it to the Graphics2D (now all objects drawn would be rotated until a new transform be assigned), then drew the one object that needed to be drawn rotated (which therefore had the newly-created rotation transform applied to it), and then restored the original, non-rotating transform to the Graphics2D object via:
g2.setTransform(oldTransform);
That way, the transform that would be applied to subsequent objects would be the original, non-rotating transform.

Categories