I am trying to create a collision detection game, using Java eclipse I know i ne
ID: 3566488 • Letter: I
Question
I am trying to create a collision detection game, using Java eclipse I know i need a board, alien, craft and missiles But I was wondering if anyone can explain this code for collision and if I could use this in the game. ---------------------------------------------------------------------------------------- package collision; import javax.swing.JFrame; public class Collision extends JFrame { public Collision() { add(new Board()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 300); setLocationRelativeTo(null); setTitle("Collision"); setResizable(false); setVisible(true); } public static void main(String[] args) { new Collision(); } }
Explanation / Answer
import java.awt.*; import javax.swing.*; import java.lang.Math; public class VGBKernel extends JPanel{ public Rectangle screen, bounds; // The screen area and boundary. public JFrame frame; // A JFrame to put the graphics into. public VGTimerTask vgTask; // The TimerTask that runs the game. public VGBall ball; // The game ball, a subclass of Rectangle. private Brick brick; // A brick for the ball to interact with. // Create a constructor method: public VGBKernel(){ super(); screen = new Rectangle(0, 0, 600, 400); bounds = new Rectangle(0, 0, 600, 400); // Give some temporary values. ball = new VGBall(); frame = new JFrame("VGBKernel"); vgTask = new VGTimerTask(); brick = new Brick(); } // Create an inner TimerTask class that has access to the // members of the VGBKernel. class VGTimerTask extends TimerTask{ public void run(){ ball.move(); frame.repaint(); } } // Create an inner VGBall class that has our game logic in it. class VGBall extends Rectangle{ int xVel, yVel; // The ball's velocity. Color ballColor; // The color of the ball. public VGBall(){ super(0, 0, 20, 20); xVel = width/4; yVel = height/4; ballColor=new Color(0, 0, 128); } // Instance methods for VGBall public void move(){ // Move the ball according to the game rules. x+=xVel; // Move horizontally. y+=yVel; // Move vertically. // Detect edges and bounce if necessary. if (x > (bounds.width - width)){ xVel = -xVel; // reverse movement. x = bounds.width - width; // Set location to screen edge. } if (y > (bounds.height - height)){ yVel = -yVel; // reverse movement. y = bounds.height - height; } if (xRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.