Draw shapes where their methods are in another class - java

I need to create a GUI for a game and I will need to display on the screen the weapon and the shield. I need to modify the program so it displays the weapon and shield, however their properties are in another class. I know I will have to extend the JPanel class and overrite its paintComponent() method.
public class GraphicsUtil {
private static final int MUZZLE_FRACTION = 3;
private static final Color MUZZLE_COLOR = Color.MAGENTA;
public static void drawShield(IShield shield, Graphics g, GameSpace gameSpace, double origHealth) {
drawPiece(shield, g, gameSpace, origHealth);
}
public static void drawWeapon(IWeapon weapon, Graphics g,
GameSpace gameSpace, double origHealth) {
Color oldColor = g.getColor();
drawPiece(weapon, g, gameSpace, origHealth);
double orientation = weapon.getOrientation();
int x1 = gameSpace.convertToScreenX(weapon.getXPos());
int y1 = gameSpace.convertToScreenY(weapon.getYPos());
int radius = gameSpace.convertToScreenDistance(weapon.getRadius());
int x2 = gameSpace.convertToScreenX(weapon.getXPos()
+ weapon.getRadius() * Math.cos(weapon.getOrientation()));
int y2 = gameSpace.convertToScreenY(weapon.getYPos()
+ weapon.getRadius() * Math.sin(weapon.getOrientation()));
double frac = 1 - 1f / MUZZLE_FRACTION;
int muzzleCentreX
= x1 + (int) Math.round(frac * radius * Math.cos(orientation));
int muzzleCentreY
= y1 - (int) Math.round(frac * radius * Math.sin(orientation));
int muzzleRadius = radius / MUZZLE_FRACTION;
int topMuzzleX = muzzleCentreX - muzzleRadius;
int topMuzzleY = muzzleCentreY - muzzleRadius;
g.setColor(MUZZLE_COLOR);
g.fillOval(topMuzzleX, topMuzzleY, 2 * muzzleRadius, 2 * muzzleRadius);
g.setColor(Color.BLACK);
g.drawLine(x1, y1, x2, y2);
g.setColor(oldColor);
}
public static boolean isInMuzzle(IPiece piece, double x, double y) {
boolean result;
if (piece instanceof IWeapon) {
IWeapon weapon = (IWeapon) piece;
double radius = weapon.getRadius();
double orientation = weapon.getOrientation();
double frac = 1 - 1f / MUZZLE_FRACTION;
double cx = piece.getXPos() + frac * radius * Math.cos(orientation);
double cy = piece.getYPos() + frac * radius * Math.sin(orientation);
double dx = x - cx;
double dy = y - cy;
double dist = Math.sqrt(dx * dx + dy * dy);
result = dist <= radius / MUZZLE_FRACTION;
} else {
result = false;
}
return result;
}
public static double getAngle(double x1, double y1, double x2, double y2) {
double dx = x2 - x1;
double dy = y2 - y1;
double hypotenuse = Math.sqrt(dx * dx + dy * dy);
double angle;
if (dy > 0) {
angle = Math.acos(dx / hypotenuse);
} else {
angle = 2 * Math.PI - Math.acos(dx / hypotenuse);
}
return angle;
}
private static void drawPiece(IPiece piece, Graphics g, GameSpace gameSpace,
double maxHealth) {
Color oldColor = g.getColor();
int centreX = gameSpace.convertToScreenX(piece.getXPos());
int centreY = gameSpace.convertToScreenY(piece.getYPos());
int displayRadius = gameSpace.convertToScreenDistance(piece.getRadius());
int topX = centreX - displayRadius;
int topY = centreY - displayRadius;
if (piece.getOwner() == 0) {
g.setColor(Color.CYAN);
} else {
g.setColor(Color.PINK);
}
g.drawOval(topX, topY, 2 * displayRadius, 2 * displayRadius);
int healthRadius
= (int) Math.round(displayRadius * piece.getHealth() / maxHealth);
int topHealthX = centreX - healthRadius;
int topHealthY = centreY - healthRadius;
g.fillOval(topHealthX, topHealthY, 2 * healthRadius, 2 * healthRadius);
String name = piece.getName();
if (name != null) {
g.setColor(Color.BLACK);
g.drawString(name, centreX, centreY);
}
g.setColor(oldColor);
}
}
This is my main method:
public class Main extends JPanel {
public Main(){
setSize(new Dimension(400,400));
setPreferredSize(new Dimension(400,400));
GraphicsUtil object = new GraphicsUtil();
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
}
public static void main(String[] args) {
Main window = new Main();
JFrame frame = new JFrame("RICOCHET");
frame.add(window);
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
How do I call those methods? What do I need to do in order to they appear in my frame? Thanks.

Presumably you have created one or more weapons or pieces. In your paintComponent() method, just call
GraphicsUtil.drawWeapon( myWeapon, g, ... );

Related

Implemention of DDA algorithm

I am trying to implement DDA algorithm in Java to draw a line. The Line Rasterizer implements an interface. Then I call the rasterizeLine function in class named Canva. The LineRasterizes successfully gets x and y points. No errors are thrown up, however there has to be some logical problem with the algorithm, because the line is not being drawed. Can you help me find the logical mistake?
Interface
package rasterops;
import rasterdata.RasterImage;
public interface LineRasterizer<PixelType> {
RasterImage<PixelType> rasterizeLine(RasterImage<PixelType> img,
double x1, double y1, double x2, double y2,
PixelType value);
}
Line Rasterizer
package rasterops;
import rasterdata.RasterImage;
public class LineRasterizerDDA<PixelType> implements LineRasterizer <PixelType> {
#Override
public RasterImage<PixelType> rasterizeLine(RasterImage<PixelType> img, double x1, double y1, double x2, double y2, PixelType value) {
double dy = y2-y1;
double dx = x2-x1;
double k = dy/dx;
double y = y1;
RasterImage<PixelType> result = img;
for( double x = x1; x <= x2; x++ ){
result = result.withPixel((int)x, (int)Math.round(y), value);
y = y1 + k;
}
return result;
}
}
Canva - calling the function
panel.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
previousX = e.getX();
previousY = e.getY();
}
});
panel.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
final double startX = previousX / (panel.getWidth() - 1.0); //k zamysleni: proc 1.0 a ne 1?
final double startY = 1 - previousY / (panel.getHeight() - 1.0);
final double endX = e.getX() / (panel.getWidth() - 1.0);
final double endY = 1 - e.getY() / (panel.getHeight() - 1.0);
clear(); // zkuste zakomentovat
rasterImage = liner.rasterizeLine(rasterImage,
startX, startY, endX, endY,
0xffff00);
panel.repaint();
}
});
This line:
y = y1 + k;
keeps assigning the same value to y, because y1 and k aren't changing.
Example output, drawing line between (0,0) and (10, 10):
O..........
.OOOOOOOOOO
...........
...........
...........
...........
...........
...........
...........
...........
...........
You may mean:
y = y + k;
or y += k;.
Example output, drawing line between (0,0) and (10, 10):
O..........
.O.........
..O........
...O.......
....O......
.....O.....
......O....
.......O...
........O..
.........O.
..........O

Java draw 3d points to 2d system using 3d projection

I have tried to follow the Wikipedia page on 3d projection to draw my own 3d line using java and AWT with Swing.
The output file that is created as a result of the rendering doesn't contain anything.
What have I done wrong?
Why isn't this producing an image file that has points on it?
Are my formulas off?
I was following this Wikipedia page as my reference: https://en.wikipedia.org/wiki/3D_projection#Perspective_projection
I have a set of points which are generated using a loop.
I then calculate the position of the 3d coordinate to 2d without using matrices, like one of the suggested method in the link.
Have I miss-interpreted something or not implemented something?
Any help and feedback are welcome.
I known nothing is drawn to the window. That isn't a priority at the moment. The priority it's getting the algorithms to work.
public class Window {
JFrame f = new JFrame();
public Window() {
JPanel p = new JPanel();
render();
f.add(p);
f.setSize(500, 500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Window w = new Window();
}
void render() {
BufferedImage image = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.red);
for (int i = 0; i < 10; i++) {
Vector3 point = new Vector3(1 + i, 2, 1 + i);
int x = calculateBX(point, new Vector3(0, 0, 0));
int y = calculateBY(point, new Vector3(1, 1, 1));
g.drawLine(x, y, x, y);
}
try {
File outputfile = new File("saved.png");
ImageIO.write(image, "png", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
}
double calculatDX(Vector3 v, Vector3 camera) {
double cx = Math.cos(0);
double cy = Math.cos(0);
double cz = Math.cos(0);
double sx = Math.sin(0);
double sy = Math.sin(0);
double sz = Math.sin(0);
int x = v.getX() - camera.getX();
int y = v.getY() - camera.getY();
int z = v.getZ() - camera.getZ();
double dx = cy * ((sz) * (y) + (cz) * (x)) - (sy) * (z);
return dx;
}
double calculatDY(Vector3 v, Vector3 camera) {
double cx = Math.cos(0);
double cy = Math.cos(0);
double cz = Math.cos(0);
double sx = Math.sin(0);
double sy = Math.sin(0);
double sz = Math.sin(0);
int x = v.getX() - camera.getX();
int y = v.getY() - camera.getY();
int z = v.getZ() - camera.getZ();
double dy = sx * ((cy) * (z) + (sy) * ((sz) * (y) + (cz) * (x))) + (cx) * (cz * (y) - sz * x);
return dy;
}
double calculatDZ(Vector3 v, Vector3 camera) {
double cx = Math.cos(0);
double cy = Math.cos(0);
double cz = Math.cos(0);
double sx = Math.sin(0);
double sy = Math.sin(0);
double sz = Math.sin(0);
int x = v.getX() - camera.getX();
int y = v.getY() - camera.getY();
int z = v.getZ() - camera.getZ();
double dz = cx * ((cy) * (z) + (sy) * ((sz) * (y) + (cz) * (x))) - (sx) * (cz * (y) - sz * x);
return dz;
}
int calculateBX(Vector3 v, Vector3 camera) {
int ez = camera.getZ();
int ex = camera.getX();
double dz = calculatDZ(v, camera);
double dx = calculatDX(v, camera);
return (int) ((ez / dz) * dx) - ex;
}
int calculateBY(Vector3 v, Vector3 camera) {
int ez = camera.getZ();
int ey = camera.getY();
double dz = calculatDZ(v, camera);
double dy = calculatDY(v, camera);
return (int) ((ez / dz) * dy) - ey;
}
}
Vector Class
public class Vector3 {
private int x, y, z;
public Vector3(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
}

How to draw a perfect triangle inside a circle orientated like a play button

I want to create a button which is a circle but has a triangle in the middle.
For a send button. I tried using xml and drawable but there are always problems when it comes to screensize and views are not centered always etc..
So how can I do that using just a canvas?
Like how do I get the points I need to draw, say, given the radius of circle, and a scale of sorts, give me points for the triangle and draw the circle.
Here is a image of what I want
I recently created something very similar to what you want..
Take a look at this: https://www.desmos.com/calculator/2wpnxwwnty
To see how the math/scaling works.
This is the class which resulted:
public class TriangleInscribedCircle {
private Triangle inscribedTriangle;
private double s = 1;
private double r = 100;
public TriangleInscribedCircle(float radius, float scale) {
setScale(scale);
this.r = radius;
calculateTriangle();
}
public Triangle getInscribedTriangle() {
return this.inscribedTriangle;
}
public double getScale() {
return this.s;
}
public void setScale(double scale) {
if (scale < 0 || scale > 12) {
throw new IllegalArgumentException("Scale must be between 0 and 12.");
}
this.s = scale;
calculateTriangle();
}
public double getCircleRadius() {
return this.r;
}
public void setCircleRadius(double radius) {
this.r = radius;
calculateTriangle();
}
private void calculateTriangle() {
double u = -((r) / (s + 1)) + r;
double x = (6 * u + 10 * r - Math.sqrt(36 * Math.pow(r, 2) + 24 * r * u - 12 * Math.pow(u, 2))) / (8);
double ax = x;
double ay = -Math.tan(Math.toRadians(30)) * (x - 2 * r + u) + r;
double bx = -u + 2 * r;
double by = r;
double cx = x;
double cy = Math.tan(Math.toRadians(30)) * (x - 2 * r + u) + r;
Point a = new Point(ax, ay);
Point b = new Point(bx, by);
Point c = new Point(cx, cy);
if (this.inscribedTriangle == null) {
this.inscribedTriangle = new Triangle(a, b, c);
} else {
this.inscribedTriangle.setA(a);
this.inscribedTriangle.setB(b);
this.inscribedTriangle.setC(c);
}
}
}
then inside your custom view
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
int radius = width / 2;
canvas.drawCircle(width / 2, height / 2, radius, mTextFieldEmpty ? mCircleDisabledPaint : mCirclePaint);
canvas.drawPath(mTrianglePath, mTextFieldEmpty ? mTriangleDisabledPaint : mTrianglePaint);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mTriangle = new TriangleInscribedCircle(w / 2, 1);
calculatePath();
}
private void calculatePath() {
mTrianglePath.reset();
mTrianglePath.moveTo((int) mTriangle.getInscribedTriangle().getA().x, (int) mTriangle.getInscribedTriangle().getA().y);
mTrianglePath.lineTo((int) mTriangle.getInscribedTriangle().getB().x, (int) mTriangle.getInscribedTriangle().getB().y);
mTrianglePath.lineTo((int) mTriangle.getInscribedTriangle().getC().x, (int) mTriangle.getInscribedTriangle().getC().y);
mTrianglePath.lineTo((int) mTriangle.getInscribedTriangle().getA().x, (int) mTriangle.getInscribedTriangle().getA().y);
}

How to move an object using radians?

I've got a problem couse I need to move my ball and it just stand still. I've succed moving it with a simple function (x=x+1) but when it comes to radians it just doesnt work. I've read some posts here and I thought I'm making it in the right way, but its obvious I've missed something :)
Here is my Ball class:
public class Ball {
int x = 0;
int y = 0;
int rightleft = 1;
int updown = 1;
private static final int sizeBall = 30;
float angle = 120;
float angleInRadians = (float) (angle*Math.PI/180);
private Main main;
public Ball(Main main){
this.main=main;
}
// That function should move my ball
void move() {
x = (int) (x + Math.cos(angleInRadians));
y= (int) (x+Math.sin(angleInRadians));
}
void paint(Graphics2D g) {
g.setColor(Color.red);
g.fillOval(x, y, sizeBall, sizeBall);
}
public Rectangle getSize(){
return new Rectangle(x,y,sizeBall,sizeBall);
}
}
And here is my Main class:
public class Main extends JPanel {
Ball ball = new Ball(this);
private void moveBall() throws InterruptedException{
ball.move();
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
ball.paint(g2d);
}
public static void main(String[] args) throws InterruptedException {
// TODO code application logic here
JFrame okno = new JFrame("TEST");
Main main = new Main();
okno.add(main);
okno.setSize(500,500);
okno.setVisible(true);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while(true){
main.moveBall();
main.repaint();
Thread.sleep(10);
}
}
}
Do you know where is my mistake?
x and y will always = 0. Understand that they are 0 to begin with, and then you add a sine or cose to them which is guaranteed to be < 1.
x = (int) (x + Math.cos(angleInRadians));
y = (int) (x+Math.sin(angleInRadians));
So 0 + a number < 1 will be < 1.
Then when you cast to int the number < 1 will become 0.
Also
use a Swing Timer not a while (true) loop.
override JPanel's paintComponent method, not its paint method for smoother animation.
I would use double numbers to represent my x and y values, and only cast or round when using them to draw.
I'm not sure what trajectory that you're aiming for, but your current code (if it worked) does not move in a polar way, but rather always at 45% angle from the current point.
For example, this GUI is created by the code below:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyPolar extends JPanel {
private static final int BI_W = 400;
private static final int BI_H = BI_W;
private static final int CTR_X = BI_W / 2;
private static final int CTR_Y = BI_H / 2;
private static final Color AXIS_COLOR = Color.black;
private static final Color GRID_LINE_COLOR = Color.LIGHT_GRAY;
private static final Color DRAWING_COLOR = Color.RED;
private static final float AXIS_LINE_WIDTH = 4f;
private static final double SCALE = BI_W / (2 * 1.25);
private static final float GRID_LINE_WIDTH = 2f;
private static final float DRAWING_WIDTH = 2f;
private static final double DELTA_THETA = Math.PI / (2 * 360);
private static final int TIMER_DELAY = 20;
private BufferedImage axiImg;
private List<Point> ptList = new ArrayList<>();
private double theta = 0;
public MyPolar() {
axiImg = createAxiImg();
int x = xEquation(theta);
int y = yEquation(theta);
ptList.add(new Point(x, y));
new Timer(TIMER_DELAY, new TimerListener()).start();
}
private int xEquation(double theta) {
double r = 2 * Math.sin(4 * theta);
return (int) (SCALE * 0.5 * r * Math.cos(theta)) + CTR_X;
}
private int yEquation(double theta) {
double r = 2 * Math.sin(4 * theta);
return (int) (SCALE * 0.5 * r * Math.sin(theta)) + CTR_Y;
}
private BufferedImage createAxiImg() {
BufferedImage img = new BufferedImage(BI_W, BI_H, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(AXIS_COLOR);
g2.setStroke(new BasicStroke(AXIS_LINE_WIDTH));
int x1 = 0;
int y1 = CTR_Y;
int x2 = BI_W;
int y2 = y1;
g2.drawLine(x1, y1, x2, y2);
x1 = CTR_X;
y1 = 0;
x2 = x1;
y2 = BI_H;
g2.drawLine(x1, y1, x2, y2);
g2.setColor(GRID_LINE_COLOR);
g2.setStroke(new BasicStroke(GRID_LINE_WIDTH));
x1 = (int) (CTR_X - BI_H * 0.5 * Math.tan(Math.PI / 6));
y1 = BI_H;
x2 = (int) (CTR_X + BI_H * 0.5 * Math.tan(Math.PI / 6));
y2 = 0;
g2.drawLine(x1, y1, x2, y2);
x1 = BI_W - x1;
x2 = BI_W - x2;
g2.drawLine(x1, y1, x2, y2);
x1 = (int) (CTR_X - BI_H * 0.5 * Math.tan(Math.PI / 3));
y1 = BI_H;
x2 = (int) (CTR_X + BI_H * 0.5 * Math.tan(Math.PI / 3));
y2 = 0;
g2.drawLine(x1, y1, x2, y2);
x1 = BI_W - x1;
x2 = BI_W - x2;
g2.drawLine(x1, y1, x2, y2);
for (int i = 1; i < 4; i++) {
int x = (int) (CTR_X - i * SCALE / 2.0);
int y = x;
int width = (int) (i * SCALE);
int height = width;
g2.drawOval(x, y, width, height);
}
g2.dispose();
return img;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (axiImg != null) {
g2.drawImage(axiImg, 0, 0, null);
}
g2.setColor(DRAWING_COLOR);
g2.setStroke(new BasicStroke(DRAWING_WIDTH));
Point prev = null;
for (Point point : ptList) {
if (prev != null) {
int x1 = prev.x;
int y1 = prev.y;
int x2 = point.x;
int y2 = point.y;
g2.drawLine(x1, y1, x2, y2);
}
prev = point;
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(BI_W, BI_H);
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
theta += DELTA_THETA;
if (theta > 2 * Math.PI) {
((Timer) e.getSource()).stop();
} else {
int x = xEquation(theta);
int y = yEquation(theta);
ptList.add(new Point(x, y));
}
repaint();
}
}
private static void createAndShowGui() {
MyPolar mainPanel = new MyPolar();
JFrame frame = new JFrame("MyPolar");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setResizable(false);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

How to make a collision detection in java?

I have a two image that moves in a random direction. Now, if that images would bump each other I want it to disappear and that is my problem about making a collision detection. Could someone help me about this problem?
Here is the code:
public class HumanBeing extends Sprite implements ImageObserver
{
private java.awt.Image humanImage;
private final World world;
private double x;
private double y;
private double speed;
private double direction = 1;
private java.util.List<Sprite> objects = new ArrayList<Sprite>();
private double angle;
public HumanBeing(World world, double x, double y, double speed)
{
this.world =world;
this.x = x;
this.y = y;
this.speed = convertToMeterPerSecond(speed);
URL iU = this.getClass().getResource("human.jpg");
ImageIcon icon = new ImageIcon(iU);
humanImage = icon.getImage();
objects.add(this);
}
public Image getImage()
{
return humanImage;
}
#Override
public void move(long dt)
{
double dt_s = dt / 1e9;
double dx_m = speed * dt_s * Math.sin(angle);
double dy_m = speed * dt_s * Math.cos(angle);
final double right_wall = world.x1_world;
final double up_wall = world.y1_world;
final double down_wall = 0.0;
final double left_wall = 0.0;
x += dx_m;
y += dy_m;
if (x >= right_wall)
{
setRandomDirection();
}
if (y > up_wall)
{
setRandomDirection();
}
if (x <= left_wall)
{
setRandomDirection();
}
if (y < down_wall)
{
setRandomDirection();
}
}
public void setRandomDirection()
{
HumanBeing humanbeing = this;
humanbeing.setAngle(Math.PI * 2 * Math.random());
}
#Override
public void render(Graphics2D g2d)
{
AffineTransform t = g2d.getTransform();
final double humanHeight = 1.6;// meter
final double humanWidth = 1.8; //meter
final double foot_position_y = humanHeight;
final double foot_position_x = humanWidth / 2;
int xx = world.convertToPixelX(x - foot_position_x); // to find the upper-left corner
int yy = world.convertToPixelY(y + foot_position_y); // to find the upper-left corner
g2d.translate(xx, yy);
// ratio for actual Image size
double x_expected_pixels = humanHeight * board.meter;
double y_expected_pixels = humanWidth * board.meter;
double w = ((ToolkitImage) humanImage).getWidth();
double h = ((ToolkitImage) humanImage).getHeight();
double x_s = x_expected_pixels / w;
double y_s = y_expected_pixels / h;
g2d.scale(x_s, y_s);
g2d.drawImage(getImage(), 0, 0, this); // upper left corner
g2d.setColor(Color.BLACK);
g2d.setTransform(t);
}
#Override
public void moveAt(double distance_x, double distance_y)
{
this.x = distance_x;
this.y = distance_y;
}
#Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
{
return false;
}
public void setAngle(double angle)
{
this.angle = angle;
}
}
this is my HumanBeing class
public class Chicken extends Sprite implements ImageObserver
{
private java.awt.Image chickenImage;
private final World world;
private double x;
private double y;
private double speed;
private double angle;
public Chicken(World world, double x, double y, double speed)
{
this.world = world;
this.x = x;
this.y = y;
this.speed = convertToMeterPerSecond(speed);
URL iU = this.getClass().getResource("chicken.gif");
ImageIcon icon = new ImageIcon(iU);
chickenImage = icon.getImage();
}
public Image getImage()
{
return chickenImage;
}
public void move(long dt)
{
double dt_s = dt / 1e9;
double dx_m = speed * dt_s * Math.sin(angle);
double dy_m = speed * dt_s * Math.cos(angle);
final double right_wall = world.x1_world;
final double up_wall = world.y1_world;
final double down_wall = 0.0;
final double left_wall = 0.0;
x += dx_m;
y += dy_m;
if (x >= right_wall)
{
x = right_wall;
setRandomDirection();
}
if (y > up_wall)
{
y = up_wall;
setRandomDirection();
}
if (x <= left_wall)
{
x = left_wall;
setRandomDirection();
}
if (y < down_wall)
{
y = down_wall;
setRandomDirection();
}
}
public void setRandomDirection()
{
Chicken chicken = this;
chicken.setAngle(Math.PI * 2 * Math.random());
}
#Override
public void render(Graphics2D g2d)
{
AffineTransform t = g2d.getTransform();
double height = 0.3; //meter
double width = 0.3; //meter
double chicken_footy = height;
double chicken_footx = width/2;
int xx = world.convertToPixelX(x - chicken_footx);
int yy = world.convertToPixelY(y + chicken_footy);
g2d.translate(xx, yy);
double x_expected_pixels = width * board.meter;
double y_expected_pixels = height * board.meter;
double x_s = x_expected_pixels / ((ToolkitImage) chickenImage).getWidth();
double y_s = y_expected_pixels / ((ToolkitImage) chickenImage).getHeight();
g2d.scale(x_s, y_s);
g2d.drawImage(getImage(), 0, 0, this);
g2d.setColor(Color.BLACK);
g2d.setTransform(t);
}
public void moveAt(double distance_x, double distance_y)
{
this.x = (int) distance_x;
this.y = (int) distance_y;
}
#Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
{
return true;
}
public void setAngle(double angle)
{
this.angle = angle;
}
}
this is my chicken class
Draw invisible Rectangle around your sprites as like Box's and than use below method to check whether they are intersecting or not :)
http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Rectangle.html#intersects(java.awt.Rectangle)
if(rect.intersect(anotherRect))
{
disappear();
}
Good luck

Categories

Resources