make image point toward specific location in java - java

BEFORE YOU MARK IT AS DUPLICATE
I have searched a lot in the internet for that and tried every solution, but no one does it the same way I do it. In my case the rotation is in a sperate class.
I have created a java class that inherits JLabel class, in my class I have an arrow BufferedImage which I draw using the paintComponent(Graphics g) method.
I am trying to make the arrow point to a specific point (which I get from a different method) but something goes wrong and the arrow rotates to the wrong direction.
I THINK: it doesn't calculate correctly because the imageLocation is relative to the label.
Here is my code:
package pkg1;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public final class ImageLabel extends JLabel {
private float angle = 0.0f; // in radians
private Point imageLocation = new Point();
private File imageFile = null;
private Dimension imageSize = new Dimension(50, 50);
private BufferedImage bi;
private BufferedImage resizeImage(BufferedImage originalImage, int img_width, int img_height) {
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizedImage = new BufferedImage(img_width, img_height, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, img_width, img_height, null);
g.dispose();
return resizedImage;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (bi == null) {
return;
}
imageLocation = new Point(getWidth() / 2 - bi.getWidth() / 2, getHeight() / 2 - bi.getHeight() / 2);
Graphics2D g2 = (Graphics2D) g;
g2.rotate(angle, imageLocation.x + bi.getWidth() / 2, imageLocation.y + bi.getHeight() / 2);
g2.drawImage(bi, imageLocation.x, imageLocation.y, null);
}
public void rotateImage(float angle) { // rotate the image to specific angle
this.angle = (float) Math.toRadians(angle);
repaint();
}
public void pointImageToPoint(Point target) {
calculateAngle(target);
repaint();
}
private void calculateAngle(Point target) {
// calculate the angle from the center of the image
float deltaY = target.y - (imageLocation.y + bi.getHeight() / 2);
float deltaX = target.x - (imageLocation.x + bi.getWidth() / 2);
angle = (float) Math.atan2(deltaY, deltaX);
if (angle < 0) {
angle += (Math.PI * 2);
}
}
}

Okay, so two things jump out at me...
If you take a Point from outside the context of the label, you will have to translate the point into the components coordinate context
The calculateAngle seems wrong
So starting with...
private void calculateAngle(Point target) {
// calculate the angle from the center of the image
float deltaY = target.y - (imageLocation.y + bi.getHeight() / 2);
float deltaX = target.x - (imageLocation.x + bi.getWidth() / 2);
angle = (float) Math.atan2(deltaY, deltaX);
if (angle < 0) {
angle += (Math.PI * 2);
}
}
angle = (float) Math.atan2(deltaY, deltaX); should be angle = (float) Math.atan2(deltaX, deltaY); (swap the deltas)
You will find that you need to adjust the result by 180 degrees in order to get the image to point in the right direction
angle = Math.toRadians(Math.toDegrees(angle) + 180.0);
Okay, I'm an idiot, but it works :P
I'd also make use of a AffineTransform to translate and rotate the image - personally, I find it easier to deal with.
In the example, I've cheated a little. I set the translation of the AffineTransform to the centre of the component, I then rotate the context around the new origin point (0x0). I then paint the image offset by half it's height/width, thus making it appear as the if the image is been rotated about it's centre - It's late, I'm tired, it works :P
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private ImageLabel label;
public TestPane() {
setLayout(new GridBagLayout());
label = new ImageLabel();
add(label);
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
label.pointImageToPoint(e.getPoint(), TestPane.this);
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public final class ImageLabel extends JLabel {
private double angle = 0;
private Point imageLocation = new Point();
private File imageFile = null;
private Dimension imageSize = new Dimension(50, 50);
private BufferedImage bi;
public ImageLabel() {
setBorder(new LineBorder(Color.BLUE));
bi = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.setColor(Color.RED);
g2d.drawLine(25, 0, 25, 50);
g2d.drawLine(25, 0, 0, 12);
g2d.drawLine(25, 0, 50, 12);
g2d.dispose();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(bi.getWidth(), bi.getHeight());
}
protected Point centerPoint() {
return new Point(getWidth() / 2, getHeight() / 2);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (bi == null) {
return;
}
Graphics2D g2d = (Graphics2D) g.create();
AffineTransform at = g2d.getTransform();
Point center = centerPoint();
at.translate(center.x, center.y);
at.rotate(angle, 0, 0);
g2d.setTransform(at);
g2d.drawImage(bi, -bi.getWidth() / 2, -bi.getHeight() / 2, this);
g2d.dispose();
}
public void rotateImage(float angle) { // rotate the image to specific angle
this.angle = (float) Math.toRadians(angle);
repaint();
}
public void pointImageToPoint(Point target, JComponent fromContext) {
calculateAngle(target, fromContext);
repaint();
}
private void calculateAngle(Point target, JComponent fromContext) {
// calculate the angle from the center of the image
target = SwingUtilities.convertPoint(fromContext, target, this);
Point center = centerPoint();
float deltaY = target.y - center.y;
float deltaX = target.x - center.x;
angle = (float) -Math.atan2(deltaX, deltaY);
angle = Math.toRadians(Math.toDegrees(angle) + 180.0);
repaint();
}
}
}
I just want to add that using a JLabel for this purpose is overkill, a simple JPanel or JComponent would do the same job and carry a lot less overhead with it, just saying

Related

How do I draw multiple line looks like dividing the sectors of a panel Java?

I would like to know how to draw multiple line that looks like dividing the panel into sectors.
This is the example of lines that I wanted to draw
Below are the code of so far I've figured it out but it can only draw "x" line and a one horizontal line on the panel. I would like to know how is it possible for me to draw lines like the image above.
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D graphic = (Graphics2D)g;
Insets insets = getInsets();
graphic.setStroke(new BasicStroke(5.0f));
graphic.draw(new Line2D.Double(insets.left, insets.top,getWidth()-insets.right, getHeight()-insets.bottom));
graphic.draw(new Line2D.Double(insets.left,getHeight()-insets.bottom,getWidth()-insets.right,insets.top));
graphic.drawLine(0,200,800,200);
}
thank you.
There's probably a few ways you could do this, but to me, this looks like spokes on a wheel, and since I know how to calculate a point a circle, this is where I'd fall back to.
What do we know:
We know the area (size of the panel)
The number of segments/divisions we want
How to calculate a point on a circle
So with that basic information, we can devise the angle delta which would required to draw the number of divisions evenly around the center point
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected Point2D pointAt(double radians, double radius) {
double x = radius * Math.cos(radians);
double y = radius * Math.sin(radians);
return new Point2D.Double(x, y);
}
protected Point2D translate(Point2D point, Point2D to) {
Point2D newPoint = new Point2D.Double(point.getX(), point.getY());
newPoint.setLocation(point.getX() + to.getX(), point.getY() + to.getY());
return newPoint;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.BLACK);
double startAngle = 0;
double divisions = 12;
double delta = 360.0 / divisions;
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int radius = Math.min(centerX, centerY) * 2; // Overshoot the visible bounds
Point2D centerPoint = new Point2D.Double(centerX, centerY);
double angle = startAngle;
for (int index = 0; index < divisions; index++) {
Point2D point = pointAt(Math.toRadians(angle), radius);
point = translate(point, centerPoint);
g2d.draw(new Line2D.Double(centerPoint, point));
angle += delta;
}
g2d.dispose();
}
}
}
Now, if you prefer not to have the lines "overshoot", then change
int radius = Math.min(centerX, centerY) * 2; // Overshoot the visible bounds
to
int radius = Math.min(centerX, centerY);
Now, if you want it to look a little "nicer", you could consider adding
RenderingHints hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHints(hints);
into the paintComponent method before you paint anything

Drawing Line from Specific Angle in Java [duplicate]

I want to make the pacman open/close mouth animation using the easiest method.
Here is my recent code: The problem is, nothing is happening?
package ordner;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PacMan implements ActionListener {
private JFrame frame;
private DrawPanel panel;
private void initGui() {
frame = new JFrame("Pacman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new DrawPanel();
frame.add(panel);
panel.setBackground(Color.BLACK);
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
PacMan pm = new PacMan();
pm.initGui();
}
#Override
public void actionPerformed(ActionEvent e) {
panel.repaint();
}
}
and here is my draw panel:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.yellow);
g.fillArc(70,50,150,150,30,300);
int i = 0;
while ( i <= 60) {
g.fillArc(70,50,150,150,30-i,300+i+i);
try {
Thread.sleep(25);
}
catch (Exception e) {
Thread.currentThread().interrupt();
}
i++;
}
}
}
The while loop doesn't affect anything, what could be the reason for that?
Something like this might work for PacMan images. It uses a Java 2D based Shape instance to represent the form, and an AffineTransform to produce the different orientations.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import java.io.*;
import javax.imageio.ImageIO;
class PacManShape {
private double size;
private double rotation;
final int maxSize = 4;
static File home = new File(System.getProperty("user.home"));
static File images = new File(home, "images");
PacManShape(int size, double rotation) {
this.size = size;
this.rotation = rotation;
}
public Area getPacManShape(double jaws) {
Area area = new Area(new Ellipse2D.Double(0d, 0d, size, size));
double x1 = size / 2 + (2d * size * Math.cos(jaws / 2d));
double y1 = size / 2 + (2d * size * Math.sin(jaws / 2d));
double x2 = x1;
double y2 = size / 2 - (2d * size * Math.sin(jaws / 2d));
Polygon mouth = new Polygon();
mouth.addPoint((int) (size / 2), (int) (size / 2));
mouth.addPoint((int) x1, (int) y1);
mouth.addPoint((int) x2, (int) y2);
mouth.addPoint((int) (size / 2), (int) (size / 2));
area.subtract(new Area(mouth));
return area;
}
public BufferedImage getPacManImage(double angle, Color color) {
BufferedImage bi = new BufferedImage(
(int) size, (int) size, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bi.createGraphics();
g2.setColor(color);
g2.fillRect(0, 0, (int) size, (int) size);
AffineTransform rotate = AffineTransform.getRotateInstance(
rotation, size / 2, size / 2);
g2.setTransform(rotate);
Area pacMan = getPacManShape(angle);
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.YELLOW);
float[] dist = {.15f, .9f};
Color[] colors = {Color.YELLOW, Color.ORANGE};
Point2D center = new Point2D.Double(size / 2, size / 2);
RadialGradientPaint radial = new RadialGradientPaint(
center, (float) ((size / 2) - 2f), dist, colors);
g2.setPaint(radial);
g2.fill(pacMan);
GradientPaint gradient = new GradientPaint(
0, 0, new Color(255, 255, 225, 220),
(int) (size / 3), 0, new Color(255, 255, 255, 0));
g2.setPaint(gradient);
g2.fill(pacMan);
g2.dispose();
return bi;
}
public void savePacManImage(int q, int num) throws IOException {
double angle = Math.PI*2 / 3d * ((double) num / (double) maxSize);
BufferedImage bi = getPacManImage(angle, Color.WHITE);
images.mkdirs();
File img = new File(images, "PacMan-" + q + "x" + num + ".gif");
ImageIO.write(bi, "gif", img);
}
public static void main(String[] args) {
try {
for (int ii = 0; ii < 4; ii++) {
PacManShape pms = new PacManShape(100, (double) ii * Math.PI / 2d);
for (int jj = 0; jj <= pms.maxSize; jj++) {
pms.savePacManImage(ii, jj);
}
}
Desktop.getDesktop().open(images);
} catch (IOException ex) {
ex.printStackTrace();
}
Runnable r = new Runnable() {
#Override
public void run() {
JPanel gui = new JPanel(new BorderLayout());
gui.add(new PacManComponent());
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class PacManComponent extends JPanel {
double angle = 0d;
int preferredSize = 100;
double diff = Math.PI / 8;
boolean chomp = true;
Timer timer;
PacManComponent() {
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
};
timer = new Timer(180, listener);
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(preferredSize, preferredSize);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
//double size = (getWidth() < getHeight() ? getWidth() : getHeight());
if (angle > 2 * Math.PI / 3) {
chomp = true;
} else if (angle < 0.01) {
chomp = false;
}
if (chomp) {
angle -= diff;
} else {
angle += diff;
}
PacManShape pms = new PacManShape(100, 0d);
Image image = pms.getPacManImage(angle, new Color(0, 0, 0, 0));
g2.drawImage(image, 0, 0, this);
g2.dispose();
}
}
If you wanted to transform & render images at run-time, try starting with this series of PNG format images that uses partial transparency to soften the edges.
For the animation, you could use a Swing Timer to move the Pacman graphic as well as adjusting the angle by which the "mouth" opens, by varying the parameters used by fillArc.
Interaction with KeyEvents for movement control can be acheived using Key Bindings.
Also, I would move the paint functionality to a paintComponent method in a sub-classed JComponent for better paint performance.
Related: Painting with Swing
Edit:
As youre starting Java there are a number of tasks to get working first
Create the JComponent based class with a static Pacman graphic. Move your painting logic to paintComponent
Get the Swing Timer functionality working. Follow the Oracle guide for Timers.
Implement the Key Bindings
Other functionality such as score keeping, etc.
2d animation:
http://en.wikipedia.org/wiki/File:The_Horse_in_Motion.jpg
Pseudocode:
while programActive:
deltatime = get_time_since_last_call()
update_animation_frame(deltatime)
image = get_animation_frame()
draw_background()
draw(image)
enforce_framerate(24)
To learn and do this sort of thing in Pygame would be easy compared to Java, but unsuitable for larger projects

How to draw a line with a direction and a fixed length

I want a line to be drawn till the edge of the screen when I provide to it 2 points and an angle (for the direction). For example if the first mouse point is 4,4 and the next mouse point is 6,6 so from those points you know that the line has a North-East direction, then a line should be drawn from 4,4 till the end of the screen and passing through 6,6. Note: after the mouse gets to 6,6 the line should be drawn till the edge of the screen while the mouse is still at 6,6.
Also this should be done in MouseMoved with no clicks preferably, this means that both mouse points are obtained from MouseMoved. I tried for a whole day to get an output but no use.
You need to break you problem down...
First, you need to be able to calculate the angle between two points
double angle = Math.atan2(toY - fromY, toX - fromX);
wow, that was kind of easy (thank you Internet)
Next, we need to be able to calculate a point on the radius of circle (okay, this might sound weird, but it's the easiest solution I could think off...and I know I can solve it, thank you Internet)
toX = (int) (Math.round(fromX + (radius * Math.cos(angle))));
toY = (int) (Math.round(fromY + (radius * Math.sin(angle))));
What we're going to do is, create a circle so large that it expands beyond the visible frame boundaries and draw our line out to! Easy!
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Point from;
private Point clickTo;
private Point to;
public TestPane() {
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (to != null) {
to = null;
clickTo = null;
from = null;
}
if (from != null) {
to = e.getPoint();
clickTo = new Point(to);
double angle = Math.atan2(to.y - from.y, to.x - from.x);
int radius = Math.max(getWidth(), getHeight()) * 2;
to.x = (int) (Math.round(from.x + (radius * Math.cos(angle))));
to.y = (int) (Math.round(from.y + (radius * Math.sin(angle))));
} else {
from = e.getPoint();
}
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (from != null) {
g2d.setColor(Color.RED);
g2d.fillOval(from.x - 4, from.y - 4, 8, 8);
if (to != null) {
g2d.setColor(Color.GREEN);
g2d.fillOval(clickTo.x - 4, clickTo.y - 4, 8, 8);
g2d.setColor(Color.BLUE);
g2d.drawLine(from.x, from.y, to.x, to.y);
}
}
g2d.dispose();
}
}
}
With center anchor point....
and MouseMotionListener support
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
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.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Point from;
private Point clickTo;
private Point to;
public TestPane() {
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
from = new Point(getWidth() / 2, getHeight() / 2);
to = e.getPoint();
clickTo = new Point(to);
double angle = Math.atan2(to.y - from.y, to.x - from.x);
int radius = Math.max(getWidth(), getHeight()) * 2;
to.x = (int) (Math.round(from.x + (radius * Math.cos(angle))));
to.y = (int) (Math.round(from.y + (radius * Math.sin(angle))));
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (from != null) {
g2d.setColor(Color.RED);
g2d.fillOval(from.x - 4, from.y - 4, 8, 8);
if (to != null) {
g2d.setColor(Color.GREEN);
g2d.fillOval(clickTo.x - 4, clickTo.y - 4, 8, 8);
g2d.setColor(Color.BLUE);
g2d.drawLine(from.x, from.y, to.x, to.y);
}
}
g2d.dispose();
}
}
}
One more small thing, i need the line to have a flexible length, by that i mean it should be within the screen, and since this is a rectangle then the width and height will differ, and having a fixed length will make problems because it will be long at some parts and short at others, any idea ?
So, you need to know where the line collides with the boundaries of the rectangle, which basically boils down to line collision detection (because a rectangle is just four lines)
So, Internet to the rescue
I took the idea slightly further and made a method which took a Rectangle and a Line2D and returned either a Point2D where the collision point occurs or null if no collision occurred (in this case, we should be 99.9% guaranteed of a collision)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Point from;
private Point clickTo;
private Point to;
public TestPane() {
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
from = new Point(getWidth() / 2, getHeight() / 2);
to = e.getPoint();
clickTo = new Point(to);
double angle = Math.atan2(to.y - from.y, to.x - from.x);
int radius = Math.max(getWidth(), getHeight()) * 2;
to.x = (int) (Math.round(from.x + (radius * Math.cos(angle))));
to.y = (int) (Math.round(from.y + (radius * Math.sin(angle))));
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public Point2D getIntersectionPoint(Line2D line1, Line2D line2) {
if (!line1.intersectsLine(line2)) {
return null;
}
double px = line1.getX1(),
py = line1.getY1(),
rx = line1.getX2() - px,
ry = line1.getY2() - py;
double qx = line2.getX1(),
qy = line2.getY1(),
sx = line2.getX2() - qx,
sy = line2.getY2() - qy;
double det = sx * ry - sy * rx;
if (det == 0) {
return null;
} else {
double z = (sx * (qy - py) + sy * (px - qx)) / det;
if (z == 0 || z == 1) {
return null; // intersection at end point!
}
return new Point2D.Float(
(float) (px + z * rx), (float) (py + z * ry));
}
} // end intersection line-line
public Point2D getIntersectionPoint(Line2D line, Rectangle bounds) {
Point2D top = getIntersectionPoint(line, new Line2D.Double(bounds.x, bounds.y, bounds.x + bounds.width, bounds.y));
Point2D bottom = getIntersectionPoint(line, new Line2D.Double(bounds.x, bounds.y + bounds.height, bounds.x + bounds.width, bounds.y + bounds.height));
Point2D left = getIntersectionPoint(line, new Line2D.Double(bounds.x, bounds.y, bounds.x, bounds.y + bounds.height));
Point2D right = getIntersectionPoint(line, new Line2D.Double(bounds.x + bounds.width, bounds.y, bounds.x + bounds.width, bounds.y + bounds.height));
return top != null ? top
: bottom != null ? bottom
: left != null ? left
: right != null ? right
: null;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Rectangle bounds = new Rectangle(50, 50, getWidth() - 100, getHeight() - 100);
g2d.draw(bounds);
if (from != null) {
g2d.setColor(Color.RED);
g2d.fillOval(from.x - 4, from.y - 4, 8, 8);
if (to != null) {
g2d.setColor(Color.GREEN);
g2d.fillOval(clickTo.x - 4, clickTo.y - 4, 8, 8);
Line2D line = new Line2D.Double(from, to);
g2d.setColor(Color.BLUE);
g2d.draw(line);
Point2D intersectPoint = getIntersectionPoint(line, bounds);
g2d.setColor(Color.MAGENTA);
g2d.fill(new Ellipse2D.Double(intersectPoint.getX() - 4, intersectPoint.getY() - 4, 8, 8));
g2d.draw(new Line2D.Double(from, intersectPoint));
}
}
g2d.dispose();
}
}
}
So, know you have a projection of the line beyond the visible boundaries of the component (which would helpful in your other question) and know where the line interests the inner boundaries

How to rotate a rectangle after reaching specified position?

I would like to rotate a rectangle when e.g. y position achieve specified position. I would like to behave a rectangle as a car on a junction - just turn e.g. right. I prefer just rotate and continue.
A draft code looks like that:
Graphics2D g2d = (Graphics2D) g.create();
g2d.setPaint(new Color(150, 150, 0));
//1. when rectangle achieve 500 on y dimension just rotate left/right
if(y==500) {
_rotate = true;
g2d.rotate(Math.toRadians(90.));
}
if(_rotate) { //if rotate, continue way on x dimension
++x ;
g2d.fillRect(x, y, 20, 40);
} else { //else go to the north
--y;
g2d.fillRect(x, y, 20, 40);
}
There is a lot of information which is missing from your question.
In order to be able to rotate a shape, you need to know a few things, you need to know it's current position and it's next target position, then you can simply calculate the angle between these two points.
The question then becomes, how do you calculate these positions. There are plenty of ways you might achieve this, the following is a simple path following process.
First, we generate a path which we need to follow, we use the Shape API to calculate the points along the path. We use a simple time based animation (rather the looping through the points, we calculate the progress along the path by calculating amount of time the animation has been playing divided by the amount of time we want it to take) and picking the point which best matches our current progress.
We use a AffineTransform to rotate the player shape and the translate the resulting Shape to the required position. Ease
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class PathFollow {
public static void main(String[] args) {
new PathFollow();
}
public PathFollow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Shape pathShape;
private List<Point2D> points;
private Shape car;
private double angle;
private Point2D pos;
private int index;
protected static final double PLAY_TIME = 5000; // 5 seconds...
private Long startTime;
public TestPane() {
Path2D path = new Path2D.Double();
path.moveTo(0, 200);
path.curveTo(100, 200, 0, 100, 100, 100);
path.curveTo(200, 100, 0, 0, 200, 0);
pathShape = path;
car = new Rectangle(0, 0, 10, 10);
points = new ArrayList<>(25);
PathIterator pi = pathShape.getPathIterator(null, 0.01);
while (!pi.isDone()) {
double[] coords = new double[6];
switch (pi.currentSegment(coords)) {
case PathIterator.SEG_MOVETO:
case PathIterator.SEG_LINETO:
points.add(new Point2D.Double(coords[0], coords[1]));
break;
}
pi.next();
}
// System.out.println(points.size());
// pos = points.get(0);
// index = 1;
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (startTime == null) {
startTime = System.currentTimeMillis();
}
long playTime = System.currentTimeMillis() - startTime;
double progress = playTime / PLAY_TIME;
if (progress >= 1.0) {
progress = 1d;
((Timer) e.getSource()).stop();
}
int index = Math.min(Math.max(0, (int) (points.size() * progress)), points.size() - 1);
pos = points.get(index);
if (index < points.size() - 1) {
angle = angleTo(pos, points.get(index + 1));
}
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.draw(pathShape);
AffineTransform at = new AffineTransform();
if (pos != null) {
Rectangle bounds = car.getBounds();
at.rotate(angle, (bounds.width / 2), (bounds.width / 2));
Path2D player = new Path2D.Double(car, at);
g2d.translate(pos.getX() - (bounds.width / 2), pos.getY() - (bounds.height / 2));
g2d.draw(player);
}
g2d.dispose();
}
// In radians...
protected double angleTo(Point2D from, Point2D to) {
double angle = Math.atan2(to.getY() - from.getY(), to.getX() - from.getX());
return angle;
}
}
}

Pacman open/close mouth animation

I want to make the pacman open/close mouth animation using the easiest method.
Here is my recent code: The problem is, nothing is happening?
package ordner;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PacMan implements ActionListener {
private JFrame frame;
private DrawPanel panel;
private void initGui() {
frame = new JFrame("Pacman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new DrawPanel();
frame.add(panel);
panel.setBackground(Color.BLACK);
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
PacMan pm = new PacMan();
pm.initGui();
}
#Override
public void actionPerformed(ActionEvent e) {
panel.repaint();
}
}
and here is my draw panel:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.yellow);
g.fillArc(70,50,150,150,30,300);
int i = 0;
while ( i <= 60) {
g.fillArc(70,50,150,150,30-i,300+i+i);
try {
Thread.sleep(25);
}
catch (Exception e) {
Thread.currentThread().interrupt();
}
i++;
}
}
}
The while loop doesn't affect anything, what could be the reason for that?
Something like this might work for PacMan images. It uses a Java 2D based Shape instance to represent the form, and an AffineTransform to produce the different orientations.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import java.io.*;
import javax.imageio.ImageIO;
class PacManShape {
private double size;
private double rotation;
final int maxSize = 4;
static File home = new File(System.getProperty("user.home"));
static File images = new File(home, "images");
PacManShape(int size, double rotation) {
this.size = size;
this.rotation = rotation;
}
public Area getPacManShape(double jaws) {
Area area = new Area(new Ellipse2D.Double(0d, 0d, size, size));
double x1 = size / 2 + (2d * size * Math.cos(jaws / 2d));
double y1 = size / 2 + (2d * size * Math.sin(jaws / 2d));
double x2 = x1;
double y2 = size / 2 - (2d * size * Math.sin(jaws / 2d));
Polygon mouth = new Polygon();
mouth.addPoint((int) (size / 2), (int) (size / 2));
mouth.addPoint((int) x1, (int) y1);
mouth.addPoint((int) x2, (int) y2);
mouth.addPoint((int) (size / 2), (int) (size / 2));
area.subtract(new Area(mouth));
return area;
}
public BufferedImage getPacManImage(double angle, Color color) {
BufferedImage bi = new BufferedImage(
(int) size, (int) size, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bi.createGraphics();
g2.setColor(color);
g2.fillRect(0, 0, (int) size, (int) size);
AffineTransform rotate = AffineTransform.getRotateInstance(
rotation, size / 2, size / 2);
g2.setTransform(rotate);
Area pacMan = getPacManShape(angle);
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.YELLOW);
float[] dist = {.15f, .9f};
Color[] colors = {Color.YELLOW, Color.ORANGE};
Point2D center = new Point2D.Double(size / 2, size / 2);
RadialGradientPaint radial = new RadialGradientPaint(
center, (float) ((size / 2) - 2f), dist, colors);
g2.setPaint(radial);
g2.fill(pacMan);
GradientPaint gradient = new GradientPaint(
0, 0, new Color(255, 255, 225, 220),
(int) (size / 3), 0, new Color(255, 255, 255, 0));
g2.setPaint(gradient);
g2.fill(pacMan);
g2.dispose();
return bi;
}
public void savePacManImage(int q, int num) throws IOException {
double angle = Math.PI*2 / 3d * ((double) num / (double) maxSize);
BufferedImage bi = getPacManImage(angle, Color.WHITE);
images.mkdirs();
File img = new File(images, "PacMan-" + q + "x" + num + ".gif");
ImageIO.write(bi, "gif", img);
}
public static void main(String[] args) {
try {
for (int ii = 0; ii < 4; ii++) {
PacManShape pms = new PacManShape(100, (double) ii * Math.PI / 2d);
for (int jj = 0; jj <= pms.maxSize; jj++) {
pms.savePacManImage(ii, jj);
}
}
Desktop.getDesktop().open(images);
} catch (IOException ex) {
ex.printStackTrace();
}
Runnable r = new Runnable() {
#Override
public void run() {
JPanel gui = new JPanel(new BorderLayout());
gui.add(new PacManComponent());
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class PacManComponent extends JPanel {
double angle = 0d;
int preferredSize = 100;
double diff = Math.PI / 8;
boolean chomp = true;
Timer timer;
PacManComponent() {
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
};
timer = new Timer(180, listener);
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(preferredSize, preferredSize);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
//double size = (getWidth() < getHeight() ? getWidth() : getHeight());
if (angle > 2 * Math.PI / 3) {
chomp = true;
} else if (angle < 0.01) {
chomp = false;
}
if (chomp) {
angle -= diff;
} else {
angle += diff;
}
PacManShape pms = new PacManShape(100, 0d);
Image image = pms.getPacManImage(angle, new Color(0, 0, 0, 0));
g2.drawImage(image, 0, 0, this);
g2.dispose();
}
}
If you wanted to transform & render images at run-time, try starting with this series of PNG format images that uses partial transparency to soften the edges.
For the animation, you could use a Swing Timer to move the Pacman graphic as well as adjusting the angle by which the "mouth" opens, by varying the parameters used by fillArc.
Interaction with KeyEvents for movement control can be acheived using Key Bindings.
Also, I would move the paint functionality to a paintComponent method in a sub-classed JComponent for better paint performance.
Related: Painting with Swing
Edit:
As youre starting Java there are a number of tasks to get working first
Create the JComponent based class with a static Pacman graphic. Move your painting logic to paintComponent
Get the Swing Timer functionality working. Follow the Oracle guide for Timers.
Implement the Key Bindings
Other functionality such as score keeping, etc.
2d animation:
http://en.wikipedia.org/wiki/File:The_Horse_in_Motion.jpg
Pseudocode:
while programActive:
deltatime = get_time_since_last_call()
update_animation_frame(deltatime)
image = get_animation_frame()
draw_background()
draw(image)
enforce_framerate(24)
To learn and do this sort of thing in Pygame would be easy compared to Java, but unsuitable for larger projects

Categories

Resources