I am trying to "teleport" objects to the opposite positions whenever they get out of screen. I've managed to do this with right & bottom sides, but for some reason, which I haven't figured out, the star objects won't go off screen on TOP & LEFT sides UNLESS the lerping speed is high enough.
Preview:
Main.java
package asteroids;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Main extends Canvas implements KeyListener {
private boolean gameOver;
private BufferStrategy backBuffer;
private Dimension dimension = new Dimension(Config.WINDOW_WH[0], Config.WINDOW_WH[1]);
private List<Star> stars = new ArrayList<Star>();
private HashMap<Integer,Boolean> keyDownMap = new HashMap<Integer, Boolean>();
private Ship ship;
private Image bg;
private float starGoalX, starGoalY;
public Main() {
// Initialize Window
initWindow();
addKeyListener(this);
this.createBufferStrategy(2);
backBuffer = this.getBufferStrategy();
bg = new ImageIcon(getClass().getResource("/bg.png")).getImage();
// init variables
gameOver = false;
// Generating stars
generateStars();
// Init spaceship
ship = new Ship(25,36,"ship.png");
// Init loop
gameLoop();
}
public void initWindow(){
JFrame window = new JFrame("Asteroids");
setPreferredSize(dimension);
window.add(this);
window.pack();
window.setResizable(false);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.requestFocus();
}
public float lerp(float starGoal, float vel, float speed) {
return starGoal + speed * (vel - starGoal);
}
public void update() {
if(keyDownMap.containsKey(KeyEvent.VK_ESCAPE)){
gameOver = false;
System.exit(0);
}
for(Star s: stars) {
s.posx += lerp(this.starGoalX, s.velX, Config.lerpSpeed);
s.velX += this.starGoalX * Config.lerpSpeed;
s.posy += lerp(this.starGoalY, s.velY, Config.lerpSpeed);
s.velY += this.starGoalY * Config.lerpSpeed;
checkPos(s);
s.update();
}
}
public void checkPos(Star s) {
if(s.posx < -s.width)
s.posx = Config.WINDOW_WH[0]-s.width;
else if(s.posx > Config.WINDOW_WH[0])
s.posx = 0;
if(s.posy < -s.height)
s.posy = Config.WINDOW_WH[1]-s.height;
else if(s.posy > Config.WINDOW_WH[1])
s.posy = 0;
}
public void render(){
Graphics2D g = (Graphics2D) backBuffer.getDrawGraphics();
if (!backBuffer.contentsLost()) {
g.drawImage(this.bg,0,0,Config.WINDOW_WH[0], Config.WINDOW_WH[1], null);
// Draw Stars
g.setColor(Color.WHITE);
for(Star s: stars)
g.fillOval(s.posx - (s.width/2), s.posy - (s.height/2), s.width, s.height);
// Draw ship
g.drawImage(
this.ship.getImage(),
this.ship.posx, this.ship.posy,
this.ship.width, this.ship.height, null);
backBuffer.show();
g.dispose();
}
}
public void generateStars() {
for(int i = 0;i < 50;i++) {
int starX = new Random().nextInt(Config.WINDOW_WH[0]+100)+5;
int starY = new Random().nextInt(Config.WINDOW_WH[1]+100)+5;
stars.add(new Star(starX, starY));
}
}
public void gameLoop(){
while(!gameOver){
update();
render();
try{ Thread.sleep(20);}catch(Exception e){};
}
}
public static void main(String[] args) {
new Main();
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_LEFT) this.starGoalX = Config.lerpSpeed;
if(e.getKeyCode() == KeyEvent.VK_RIGHT) this.starGoalX = -Config.lerpSpeed;
if(e.getKeyCode() == KeyEvent.VK_UP) this.starGoalY = Config.lerpSpeed;
if(e.getKeyCode() == KeyEvent.VK_DOWN) this.starGoalY = -Config.lerpSpeed;
keyDownMap.put(e.getKeyCode(), true);
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_LEFT
|| e.getKeyCode() == KeyEvent.VK_RIGHT) this.starGoalX = 0;
if(e.getKeyCode() == KeyEvent.VK_UP
|| e.getKeyCode() == KeyEvent.VK_DOWN) this.starGoalY = 0;
keyDownMap.remove(e.getKeyCode());
}
}
Star.java
package asteroids;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.KeyEvent;
import java.awt.geom.Ellipse2D;
import java.util.HashMap;
import java.util.Random;
public class Star {
int width, height;
int posx, posy;
float velX, velY, velGoalX, velGoalY;
/** CONSTRUCTOR **/
public Star(int x, int y) {
int rand = new Random().nextInt(Config.STAR_SIZES.length);
width = Config.STAR_SIZES[rand];
height = Config.STAR_SIZES[rand];
posx = x;
posy = y;
}
public void update() {
// pass
}
}
Ship.java
package asteroids;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import javax.swing.ImageIcon;
public class Ship {
public int posx, posy;
public int width, height;
private Image image;
public Ship(int w, int h, String img) {
this.posx = Config.WINDOW_WH[0]/2;
this.posy = Config.WINDOW_WH[1]/2;
this.width = w;
this.height = h;
this.image = new ImageIcon(getClass().getResource("/"+img)).getImage();
}
public Image getImage() {
return this.image;
}
public void setPosx(int x) {posx = x;}
public void setPosy(int y) {posy = y;}
public void setImg(Image img) {
this.image = img;
}
public void update(HashMap keyDownMap) {
// pass
}
}
Config.java
package asteroids;
import java.awt.Color;
public class Config {
// MAIN CANVAS SETTINGS
public static int[] WINDOW_WH = {500, 500};
public static String WINDOW_BG_IMG = "";
public static Color WINDOW_BG_CLR = new Color(40, 42, 45);
// OBJECT SETTINGS
public static int[] STAR_SIZES = {10,5,8,3,7};
public static float lerpSpeed = 0.8f;
}
Related
I've got a Jpanel called Field(a class that extends JPanel)and i'm adding objects bullet in List and player-class as a player.
Please help.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Field extends JPanel implements ActionListener
{
Player p1 = new Player();
Move m = new Move(this);
Shoot shoot = new Shoot(this);
List<Bullet> bullets = new ArrayList<Bullet>();
//position of the player
public int x ;
public int y ;
Timer tm = new Timer(20,this);
public Field(Player p , ArrayList<Chicken> chickens)
{
p1 = p ;
setBackground(Color.black);
addMouseMotionListener(m);
addKeyListener(shoot);
tm.start();
}
class Move implements MouseMotionListener
{
public Move(Field f)
{
f.addMouseMotionListener(this);
}
#Override
public void mouseDragged(MouseEvent e)
{
// TODO Auto-generated method stub
p1.shuttlex = e.getXOnScreen()-15;
p1.shuttley = e.getYOnScreen()-50;
p1.wingLx = p1.shuttlex - p1.shuttleWidth + 2;
p1.wingY = p1.shuttley + 40;
p1.wingRx = p1.shuttlex + p1.shuttleWidth - 2;
p1.wingWid = 15;
p1.wingLen = 40;
x = e.getXOnScreen()-15;
y = e.getYOnScreen()-25;
repaint();
}
#Override
public void mouseMoved(MouseEvent e)
{
// TODO Auto-generated method stub
p1.shuttlex = e.getXOnScreen()-15;
p1.shuttley = e.getYOnScreen()-50;
p1.wingLx = p1.shuttlex - p1.shuttleWidth + 2;
p1.wingY = p1.shuttley + 40;
p1.wingRx = p1.shuttlex + p1.shuttleWidth - 2;
p1.wingWid = 15;
p1.wingLen = 40;
x = e.getXOnScreen()-15;
y = e.getYOnScreen()-25;
repaint();
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
p1.paintComponent(g);
for(Bullet fire : bullets)
{
fire.paintComponent(g);
}
}
private void addFire(Bullet fire)
{
bullets.add(fire);
}
class Shoot implements KeyListener
{
Field field;
public Shoot(Field field)
{
field.addKeyListener(this);
this.field=field;
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
char key = e.getKeyChar();
if(key == ' ')
{
field.addFire(new Bullet(x, y));
}
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
#Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
for(Bullet fire : bullets)
{
fire.y-=10;
}
repaint();
}
public void movePlayer(Player p , MouseEvent e)
{
//just moves the Player
p.shuttlex = e.getXOnScreen()-15;
p.shuttley = e.getYOnScreen()-50;
p.wingLx = p1.shuttlex - p1.shuttleWidth + 2;
p.wingY = p1.shuttley + 40;
p.wingRx = p1.shuttlex + p1.shuttleWidth - 2;
p.wingWid = 15;
p.wingLen = 40;
x = e.getXOnScreen()-15;
y = e.getYOnScreen()-25;
repaint();
}
}
And this is my bullet class:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Bullet
{
public int x , y,width =20, length=50;
public int damage = 10;
public Bullet(int x , int y)
{
this.x = x ;
this.y = y ;
}
public void paintComponent(Graphics g)
{
g.setColor(Color.red);
g.drawRect(x, y, width, length);
}
}
And my Player Class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
public class Player
{
public Player()
{
}
private int HP;
public int shuttlex = 740, shuttley = 650, shuttleWidth = 15, shuttleLength = 70;
public int wingLx = shuttlex - shuttleWidth + 2, wingY = shuttley + 40;
public int wingRx = shuttlex + shuttleWidth - 2;
public int wingWid = 15, wingLen = 40;
public void paintComponent(Graphics g)
{
g.setColor(Color.RED);
g.fillOval(shuttlex + 2, shuttley + 60, 11, 33);
g.setColor(Color.ORANGE);
g.fillOval(shuttlex + 2, shuttley + 60, 11, 20);
g.setColor(Color.BLUE);
g.fillRoundRect(shuttlex, shuttley, shuttleWidth, shuttleLength, 30, 100);
g.fillOval(wingLx, wingY, wingWid, wingLen);
g.fillOval(wingRx, wingY, wingWid, wingLen);
// g.fillRect(x, y, width, height);
}
public void gotDamaged(int damage)
{
HP-=damage;
}
public boolean isAlive()
{
if(HP>0)
return true;
return false;
}
}
it draws the player and goes where ever the mouse is.
The problem is when i type the Space key it doesn't add bullet.
whats wrong with my code ?
it doesnt show the bullet that has to be drawn
You could try KeyCode
int key = e.getKeyCode();
if(key == KeyCode.SPACE)
or Unicode value for SPACE instead of ' '.
Just a small program I quickly made to see if I could perform collisions with a rectangle object and a rotating rectangle object.
Problem arises when rotating rectangle object, the collision box doesn't rotate, only the image rotates.
In this code I tried to use shape object but and performed transformations to it, but was unsuccessful.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
public class test extends JFrame implements Runnable,KeyListener
{
MyDrawPanel playPanel = new MyDrawPanel();
Thread th= new Thread(this);
int w=500, h=539;
Rectangle s1;
Rectangle r1;
int x=50,y=50;
int spx=0;
int spy=0;
int b=0;
int spin=0,spin2=0;
Shape p1;
AffineTransform tx,ax;
public static void main (String [] args)
{
new test();
}
public test()
{
s1= new Rectangle(200,200,106,16);
p1= new Rectangle(200,200,106,16);
r1= new Rectangle(x,y,50,50);
this.setSize(w,h);
this.setVisible(true);
this.setResizable(true);
this.addKeyListener(this);
this.add(playPanel);
playPanel.setDoubleBuffered(true);
th.start();
}
public void keyPressed(KeyEvent e)
{
int key =e.getKeyCode();
if (key == KeyEvent.VK_DOWN)
{
spy=2;
}
if (key == KeyEvent.VK_UP)
{
spy=-2;
}
if (key == KeyEvent.VK_RIGHT)
{
spx=2;
}
if (key == KeyEvent.VK_LEFT)
{
spx=-2;
}
}
public void keyReleased(KeyEvent e)
{
spx=0;
spy=0;
}
public void keyTyped(KeyEvent e)
{}
public void coll()
{
if (r1.getBounds().intersects(p1.getBounds()))
{
b=1;
}
else{b=0;}
}
public void rot()
{
AffineTransform px= new AffineTransform();
px.rotate(Math.toRadians(spin),w/2,h/2);
p1=px.createTransformedShape(s1);
}
///DO TOP HEAD INTERSECT CHECKINGGGGGGGGGGGGGGGGG!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public void run ()
{
while (true)
{
rot();
r1.x+=spx;
r1.y+=spy;
spin+=2;
coll();
repaint();
try
{
Thread.sleep (30);
}
catch (InterruptedException ex)
{
}
}
}
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (b==1)
{
g2.setColor(Color.RED);
}
AffineTransform old= g2.getTransform();
//g2.rotate(Math.toRadians(spin),
//p1.getBounds().x+8,p1.getBounds().y+8);
g2.fillRect(p1.getBounds().x,p1.getBounds().y,106,16);
g2.setTransform(old);
g2.fillRect(r1.x,r1.y,r1.width,r1.height);
}
}
}
//15.31
/* ADD YOUR CODE HERE */
Used Bresenham's algorithm to find all pixels on a Line2D to detect collision between Rectangle and Line through class LineIterator.
Try like below said source, by increased value of spx and spy with difference value of 4 for moving the square faster:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Iterator;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class RotateRectangleRound extends JFrame implements KeyListener {
private static final long serialVersionUID = 9085168127541601308L;
private Rectangle stableRect;
private int cw = 400, ch = 400;
private boolean collision;
private int spx = 0, spy = 0;
private double radius = 120;
private double angleX = 0, angleY = 0;
private int rotatingVal = 0;
private Line2D line;
private LineIterator iterator;
private Point currentPoint;
private Point2D tp;
private static BasicStroke spinningStroke = new BasicStroke(8);
private static BasicStroke basicStroke = new BasicStroke(1);
private MyPanel panel;
private static boolean startWorker;
private SwingWorker<Void, Void> swingWorker;
public RotateRectangleRound() {
init();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new RotateRectangleRound();
}
});
}
private void init() {
this.setTitle("Rotate Rectangle - Paused");
this.getContentPane().setLayout(new GridLayout(1, 1));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(400, 200, 400, 400);
this.setLayout(new GridLayout(1, 1));
this.addKeyListener(this);
this.setVisible(true);
// getting the window width & height insets explicitly
cw = this.getContentPane().getWidth();
ch = this.getContentPane().getHeight();
// setting the stableRect and movableRect to between of screen except insets
stableRect = new Rectangle(20, 20, 40, 40);
angleX = 192;
angleY = 300;
this.panel = new MyPanel();
this.add(panel);
}
#Override
public void keyTyped(KeyEvent evt) {}
public void keyPressed(KeyEvent evt) {
int key = evt.getKeyCode();
if (key == KeyEvent.VK_DOWN) {
spy = 4;
moveStableRectangle();
} else if (key == KeyEvent.VK_UP) {
spy = -4;
moveStableRectangle();
} else if (key == KeyEvent.VK_RIGHT) {
spx = 4;
moveStableRectangle();
} else if (key == KeyEvent.VK_LEFT) {
spx = -4;
moveStableRectangle();
}
if (key == KeyEvent.VK_SPACE) {
startWorker = (!startWorker);
if (startWorker) {
this.setTitle("Rotate Rectangle");
collision = false;
startRotatingFromPoint();
}else {
this.setTitle("Rotate Rectangle - Paused");
}
}
}
private void moveStableRectangle() {
stableRect.x += spx;
stableRect.y += spy;
repaint();
}
public void keyReleased(KeyEvent evt) {
spx = 0;
spy = 0;
}
private void startRotatingFromPoint() {
swingWorker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
while (startWorker) {
try {
if (rotatingVal == 360)
rotatingVal = 0;
// first getting the angle x, y value for radius 100,
// second adding the half of width & height to rotate
// between screen accordingly with that w & h value
angleX = (Math.sin(Math.toRadians((double) rotatingVal)) * radius) + (cw / 2);
angleY = (Math.cos(Math.toRadians((double) rotatingVal++)) * radius) + (ch / 2);
// calculating collision
collision();
// requesting frame repainting
repaint();
Thread.sleep(10);
} catch (InterruptedException iex) {
iex.printStackTrace();
}
}
return null;
}
};
swingWorker.execute();
}
public void collision() {
if (detectCollision()) {
collision = true;
startWorker = false;
this.setTitle("Rotate Rectangle - Hitted");
} else {
collision = false;
}
}
private boolean detectCollision() {
boolean flag = false;
if(angleX < (cw/2))
line = new Line2D.Double(angleX, angleY, cw / 2, ch / 2);
else
line = new Line2D.Double(cw / 2, ch / 2, angleX, angleY);
//creating a iterator by use of Bresenham's algorithm
iterator = new LineIterator(line);
looperFor:
for (Iterator<Point2D> it = iterator; it.hasNext();) {
//getting Point2D Object of Point Iterator
tp = it.next();
currentPoint = new Point((int) tp.getX(), (int) tp.getY());
if (stableRect.contains(currentPoint)) {
flag = true;
break looperFor;
}
}
//returning the detected collision flag true or false
return flag;
}
class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
#Override
public void paintComponent(Graphics gr) {
Graphics2D g = (Graphics2D) gr;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setStroke(basicStroke);
if (collision)
g.setColor(Color.RED);
g.fillRect(stableRect.x, stableRect.y, stableRect.width, stableRect.height);
g.setStroke(spinningStroke);
g.drawLine(cw / 2, ch / 2, (int) angleX, (int) angleY);
}
}
}
Hope this would help you.
I read many other posts regarding this and I learned that the frame is set to BorderLayout by default. I added one shape to the west and one shape to the center of the frame. But still, only one shape comes up on the frame. The shape that comes up on the frame is the one whose location is at center.
Here is the code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ShapeMover {
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 400;
private static final int SHAPE_WIDTH = 50;
private static final int INITIAL_X = 30;
private static final int INITIAL_Y = 100;
private static final int rec_x = 200;
private static final int rec_y = 200;
private static final int rec_height = 30;
private static final int rec_width = 50;
private boolean recToggle = true;
private boolean circleToggle = true;
private JFrame frame;
private CircleComponent myShape;
private RectangleComponent recShape;
private JButton circle, rectangle;
private JPanel panel, panel2;
private void initialSetUp() {
frame = new JFrame();
myShape = new CircleComponent(INITIAL_X, INITIAL_Y, SHAPE_WIDTH);
recShape = new RectangleComponent(rec_x, rec_y,rec_height, rec_width);
circle = new JButton("Click for circle");
event c = new event();
circle.addActionListener(c);
rectangle = new JButton("Click for rectangle");
event2 r = new event2();
rectangle.addActionListener(r);
panel = new JPanel();
panel.add(circle);
panel.add(rectangle);
frame.add(panel, BorderLayout.NORTH);
frame.add(myShape, BorderLayout.WEST);
frame.add(recShape,BorderLayout.CENTER);
myShape.setVisible(false);
recShape.setVisible(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setVisible(true);
} //method
public class event implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(circleToggle == true){
myShape.setVisible(true);
circleToggle = false;
}
else{
myShape.setVisible(false);
circleToggle = true;
}
}
}
public class event2 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
if(recToggle == true){
recShape.setVisible(true);
recToggle = false;
}
else{
recShape.setVisible(false);
recToggle = true;
}
}
}
public static void main(String[] args) {
ShapeMover sm = new ShapeMover();
sm.initialSetUp();
} //main
} //class
I warn you the other code is pretty long.
Here is rectangle component:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JComponent;
public class RectangleComponent extends JComponent{
private CompoundShape shape2;
private Point mousePoint2;
public RectangleComponent(int x, int y, int height, int width){
shape2 = new RectangleShape(x, y, height, width);
addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent event2){
mousePoint2 = event2.getPoint();
if(!shape2.contains(mousePoint2)){
mousePoint2 = null;
}
}
});
addMouseMotionListener(new MouseMotionAdapter(){
#Override
public void mouseDragged(MouseEvent event2){
if(mousePoint2 == null){
return;
}
Point lastMousePoint2 = mousePoint2;
mousePoint2 = event2.getPoint();
double dx = mousePoint2.getX() - lastMousePoint2.getX();
double dy = mousePoint2.getY() - lastMousePoint2.getY();
shape2.translate((int) dx, (int) dy);
repaint();
}
});
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
//shape.draw(g2);
shape2.draw(g2);
} //method
}
Here is the circle Component:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JComponent;
public class CircleComponent extends JComponent{
private Circle shape2;
private Point mousePoint2;
public CircleComponent(int x, int y, int width){
shape2 = new Circle(x, y, width);
addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent event2){
mousePoint2 = event2.getPoint();
if(!shape2.contains(mousePoint2)){
mousePoint2 = null;
}
}
});
addMouseMotionListener(new MouseMotionAdapter(){
#Override
public void mouseDragged(MouseEvent event2){
if(mousePoint2 == null){
return;
}
Point lastMousePoint2 = mousePoint2;
mousePoint2 = event2.getPoint();
double dx = mousePoint2.getX() - lastMousePoint2.getX();
double dy = mousePoint2.getY() - lastMousePoint2.getY();
shape2.translate((int) dx, (int) dy);
repaint();
}
});
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
//shape.draw(g2);
shape2.draw(g2);
} //method
}
Here is circle:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
public class Circle implements CompoundShape {
private GeneralPath path = null;
private int x;
private int y;
private final int width;
public Circle(int x, int y, int width){
this.x = x;
this.y = y;
this.width = width;
}
#Override
public void draw(Graphics2D g2) {
Ellipse2D.Double c = new Ellipse2D.Double(x,y,width,width);
g2.setColor(Color.RED);
g2.fill(c);
g2.draw(c);
path = new GeneralPath();
path.append(c,false);
g2.draw(path);
}
#Override
public void translate(int dx, int dy) {
// TODO Auto-generated method stub
x = x + dx;
y = y + dy;
}
#Override
public boolean contains(Point point) {
// TODO Auto-generated method stub
if(path == null){
return false;
}
return path.contains(point);
}
}
Here is rectangle shape:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
public class RectangleShape implements CompoundShape {
private GeneralPath path = null;
private int x;
private int y;
private final int width;
private final int height;
public RectangleShape(int x, int y, int width, int height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
#Override
public void draw(Graphics2D g2) {
Rectangle r = new Rectangle(x,y,width,height);
g2.setColor(Color.BLUE);
g2.fill(r);
g2.draw(r);
path = new GeneralPath();
path.append(r,false);
g2.draw(path);
}
#Override
public void translate(int dx, int dy) {
// TODO Auto-generated method stub
x = x + dx;
y = y + dy;
}
#Override
public boolean contains(Point point) {
// TODO Auto-generated method stub
if(path == null){
return false;
}
return path.contains(point);
}
}
Here is compound shape:
import java.awt.Graphics2D;
import java.awt.Point;
public interface CompoundShape {
void draw(Graphics2D g2);
void translate(int dx, int dy);
boolean contains(Point point);
} //interface
Examples of iterating an ArrayList<Shape> can be seen in:
This answer to Get mouse detection with a dynamic shape.
This answer to 'Fill' Unicode characters in labels.
Of course, those examples are painting to an image, but once there is a Graphics (or Graphics2D as I prefer to work with) the principle is much the same. Copy/pasted from one example:
ArrayList<Shape> regions = separateShapeIntoRegions(imageShapeArea);
// ..
for (Shape region : regions) {
// ..
g.fill(region);
// ..
}
first sorry for my bad English
Hello everyone I'm developing a 2d game using java and when a want to animate a sequence of images only the last image is loaded & i don't know why my code seems Logic
So that when I press "Q" button there most be an animation there.
code:
Dude Class
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Dude {
int x, dx, y, dy;
Image still;
Image walking;
Image effet;
ImageIcon i = new ImageIcon("C:/1.gif");
ImageIcon run=new ImageIcon("C:/NeroRun.gif");
ImageIcon down=new ImageIcon("C:/nero_down.gif");
Image[]attack=new Image[15];
ImageIcon saut_effet=new ImageIcon("C:/saut_effet.gif");
ImageIcon saut=new ImageIcon("C:/saut.gif");
ImageIcon effect=new ImageIcon("C:/saut_effet.gif");
//ImageIcon attack;
public Dude() throws {
still = i.getImage();
x = 10;
y = 260;
for(int j=0;j<15;j++){
ImageIcon ii=new ImageIcon("C:/Games/frame-"+(j+1)+".gif");
attack[j] = ii.getImage();
System.out.println("Nice");
}
}
public void move(){
x = x + dx;
y = y + dy;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public Image getImage(){
return still;
}
public Image getEffet(){
return effet;
}
public void keyPressed(KeyEvent e) throws InterruptedException{
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -3;
still=run.getImage();
System.out.println("Left");
if(y==260){y+=55;}
}
if (key == KeyEvent.VK_RIGHT) {
dx = 3;
still=run.getImage();
System.out.println("Right");
if(y==260){y+=55;}
effet=null;
}
if (key == KeyEvent.VK_DOWN) {
still=down.getImage();
System.out.println("Down");
if(y==260){y+=90;}
effet=null;
}
if (key == KeyEvent.VK_UP){
if(y==260){y-=130;}
effet=effect.getImage();
still=saut.getImage();
}
if(key == KeyEvent.VK_Q){
if(y==260){y-=135;
for(int j=0;j<15;j++){
still=attack[j];
}
//attack=new ImageIcon("C:/first_attack.gif");
//still=attack.getImage();}
effet=null;
}
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT){
dx = 0;
still=i.getImage();
y=260;
effet=null;
}
if (key == KeyEvent.VK_RIGHT){
dx = 0;
still=i.getImage();
y=260;
effet=null;
}
if (key == KeyEvent.VK_DOWN){
dx = 0;
still=i.getImage();
y=260;
effet=null;
}
if (key == KeyEvent.VK_UP){
still=i.getImage();
y=260;
effet=null;
}
if (key == KeyEvent.VK_Q){
still=i.getImage();
y=260;
effet=null;
}
}
}
Borad1 Class:
package FirstTest;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
import org.newdawn.slick.SlickException;
/**
*
* #author SiLeNT J0cK3R
*/
class Board1 extends JPanel implements ActionListener{
Dude p;
Image img;
Timer time;
public Board1() throws SlickException{
p = new Dude();
addKeyListener(new AL());
setFocusable(true);
ImageIcon i = new ImageIcon("C:/Background.png");
img = i.getImage();
time = new Timer(5, this);
//Music.music();
time.start();
}
#Override
public void actionPerformed(ActionEvent e){
p.move();
repaint();
//System.out.println("Repaint");
}
#Override
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(img, 0, 0, null);
g2d.drawImage(p.getImage(), p.getX(), p.getY(),null);
//Pour animer les effets loresequ'on effectue un saut
g2d.drawImage(p.getEffet(),p.getX(),300,null);
//Pour animer les ennemies
}
private class AL extends KeyAdapter{
#Override
public void keyReleased(KeyEvent e){
p.keyReleased(e);
}
#Override
public void keyPressed (KeyEvent e){
try {
p.keyPressed(e);
} catch (InterruptedException ex) {
Logger.getLogger(Board1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
for(int j=0;j<15;j++){
still=attack[j];
}
When identifying the Q key, you seem to just walk through the animation frames (images).For an animation to be visible, some time would have to pass between each change of an animation frame.
I would suggest you take a look at some examples and tutorials. Like the Space Invaders clone found here: www.cokeandcode.com
I'm kind of a beginner when it comes to java programming, and I have a project in school where I'm going to create a game much like Icy Tower. And my question is, how am I going to write to make the character stand on the ground and be able to jump up on objects?
Here's my code so far:
Part one
package Sprites;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class jumper {
private String jump = "oka.png";
private int dx;
private int dy;
private int x;
private int y;
private Image image;
public jumper() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(jump));
image = ii.getImage();
x = 50;
y = 100;
}
public void move() {
x += dx;
y += dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return image;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -5;
ImageIcon ii = new ImageIcon(this.getClass().getResource("oki.png"));
image = ii.getImage();
}
if (key == KeyEvent.VK_RIGHT){
dx = 5;
ImageIcon ii = new ImageIcon(this.getClass().getResource("oka.png"));
image = ii.getImage();
}
if (key == KeyEvent.VK_SPACE) {
dy = -5;
}
if (key == KeyEvent.VK_DOWN) {
dy = 5;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT){
dx = 0;
}
if (key == KeyEvent.VK_SPACE) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}
}
Part two
package Sprites;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class board extends JPanel implements ActionListener {
private Timer klocka;
private jumper jumper;
public board() {
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.WHITE);
setDoubleBuffered(true);
jumper = new jumper();
klocka = new Timer(5, this);
klocka.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(jumper.getImage(), jumper.getX(), jumper.getY(), this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void actionPerformed(ActionEvent e) {
jumper.move();
repaint();
}
private class TAdapter extends KeyAdapter {
public void keyReleased(KeyEvent e) {
jumper.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
jumper.keyPressed(e);
}
}
}
Part three
package Sprites;
import javax.swing.JFrame;
public class RType extends JFrame {
public RType() {
add(new board());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
setTitle("R - type");
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new RType();
}
}
I really appreciate all the help I can get!
This might help. It's a set of tutorials aimed at helping people make tile-based games. Including side-on platform games. See http://www.tonypa.pri.ee/tbw/tut07.html. By the way, you're doing quite intensive image-loading stuff in the character movement methods. Don't do that. Cache the images first. Also, you can double-buffer your Canvas to make it smooth. See the code here for details.