I am making bouncing balls, there are icons on the labels in the codes. When I multiply the variables 'hizx','hizx2','hizx3' by -1, they only hop on the x-axis. If I write the variables 'hizy', 'hizy2', 'hizy3' in the comment line as I did, the icons get weird when the balls cross each other.Could you help?
How can I make icons bounce after touching each other?
Pictures I used
form starter
package odev5_m_metin;
import javax.swing.*;
public class giris {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
odev_intersect o1 = new odev_intersect();
o1.setVisible(true);
}
});
}
}
Main code:
package odev5_m_metin;
import javax.swing.*;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Rectangle;
public class odev_intersect extends JFrame {
private JPanel panel1;
private JLabel label1;
private JLabel label2;
private JLabel label3;
static int x,y,x2,y2,x3,y3,hizx = 5, hizy = 4,hizx2 = 5, hizy2 = 7,hizx3=5,hizy3=5;
static Timer time1;
static TimerTask g1,g2;
static Rectangle r1;
static Rectangle r2;
static Rectangle r3;
public odev_intersect() {
add(panel1);
setSize(500,500);
setTitle("Intersect Ödev");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label1.setBounds(150,150,50,50);
label2.setBounds(150,300,50,50);
label3.setBounds(450,450,50,50);
x=100;
y=200;
x2=200;
y2=200;
x3=300;
x3=300;
time1 = new Timer();
g1 = new TimerTask() {
@Override
public void run() {
r1 = new Rectangle(label1.getX(),label1.getY(),label1.getWidth(),label1.getHeight());
r2 = new Rectangle(label2.getX(),label2.getY(),label2.getWidth(),label2.getHeight());
r3 = new Rectangle(label3.getX(),label3.getY(),label3.getWidth(),label3.getHeight());
x+=hizx;
y+=hizy;
x2+=hizx2;
y2+=hizy2;
x3+=hizx3;
y3+=hizy3;
if (x>=440 || x<=0) hizx*=-1;
if (y>=410 || y<=0) hizy*=-1;
if (x2>=440 || x2<=0) hizx2*=-1;
if (y2>=410 || y2<=0) hizy2*=-1;
if (x3>=440 || x3<=0) hizx3*=-1;
if (y3>=410 || y3<=0) hizy3*=-1;
if (r1.intersects(r2) || r1.intersects(r3)) hizx*=-1; //hizy*=-1;
if (r2.intersects(r1) || r2.intersects(r3)) hizx2*=-1; //hizy2*=-1;
if (r3.intersects(r2) || r3.intersects(r1)) hizx3*=-1; //hizy3*=-1;
label1.setBounds(x,y,50,50);
label2.setBounds(x2,y2,50,50);
label3.setBounds(x3,y3,50,50);
}
};
time1.schedule(g1,0,10);
}
}