How to make a collision detection in java? - 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

Related

Did I correctly translate this pseudocode into Java?

I asked this question on Math.se a few days ago, and got the following answer in pseudocode:
Function RandomCircleInside(centerX, centerY, radius):
Let newRadius = radius * Random()
Let radians = 2.0 * 3.14159265358979323846 * Random()
Let deviation = (radius - newRadius) * Sqrt(Random())
Let newX = centerX + deviation * Cos(radians)
Let newY = centerY + deviation * Sin(radians)
Return (newX, newY, newRadius)
End Function
I changed the pseudocode to Java and added my own changes to fit my needs. The new code looks like this:
Circle createNewCircle(int centerX, int centerY, int radius, int newR, Color newColor) {
int newRadius = radius * Random();
double radians = 2.0 * 3.141592653589793 * Random();
double deviation = (radius - newRadius) * Math.sqrt(Random());
System.out.println(radius + " - " + newRadius + " * sqrt(0 or 1) = " + (radius-newRadius) + " * (0 or 1) = " + deviation);
double newX = centerX + deviation * Math.cos(radians);
System.out.println(centerX + " + " + deviation + " * cos(" + radians + ") = " + (centerX + deviation) + " * " + Math.cos(radians));
double newY = centerY + deviation * Math.sin(radians);
int newCirX = (int) newX;
int newCirY = (int) newY;
Circle newCir = new Circle(newCirX, newCirY, newR*2, newR*2, newR, newColor, true);
return newCir;
}
The code itself is supposed to create a new Circle inside of a preexisting one. I created a circle class that looks like this:
import java.awt.Color;
import java.awt.Graphics;
public class Circle {
public int X, Y, Width, Height, radius;
public Color color;
public boolean toFill;
public Circle(int x, int y, int width, int height, int radius, Color color, boolean fill) {
X = x;
Y = y;
Width = width;
Height = height;
this.radius = radius;
this.color = color;
toFill = fill;
}
public void render(Graphics g) {
g.setColor(color);
for(int i=-5; i<5; i++) {
if(toFill) {
g.fillOval(X+i, Y+i, Width-i, Height-i);
} else {
g.drawOval(X+i, Y+i, Width-i, Height-i);
}
}
}
public boolean contains(Circle pBound) {
int pBoundCenterX = pBound.X+pBound.radius;
int cirCenterX = X+radius;
int diffBetweenCentersX = Math.abs(pBoundCenterX-cirCenterX);
int pBoundCenterY = pBound.Y+pBound.radius;
int cirCenterY = Y+radius;
int diffBetweenCentersY = Math.abs(pBoundCenterY-cirCenterY);
if(diffBetweenCentersX<= (pBound.radius+radius) && diffBetweenCentersX>=Math.abs(pBound.radius-radius)) { // X
if(diffBetweenCentersY>=Math.abs(pBound.radius-radius)) { // Y
return true;
}
}
return false;
}
public int getX() {
return X;
}
public int getWidth() {
return Width;
}
public int getRadius() {
return radius;
}
public void setWidth(int width) {
Width = width;
}
public int getHeight() {
return Height;
}
public void setHeight(int height) {
Height = height;
}
public void setX(int x) {
X = x;
}
public int getY() {
return Y;
}
public void setY(int y) {
Y = y;
}
}
My way of creating the new circle is this:
if(secInGame==timesForCircle[X] && !hasChanged) { // circle 2
Circle cir1 = cir;
cir = createNewCircle(cir1.X+(cir1.Width/2), cir1.Y+(cir1.Height/2), cir1.getRadius(), 135, Color.cyan);
hasChanged = true;
circleOn++;
circ++;
}
Where cir1 is the preexisting Circle and cir is the new circle.
Is there anything I didn't code correctly? I've tried a few different variations, but they all give the same result.
Before I implemented the pseudocode, my circles looked like this:
but now it looks like this:
All of my code can be found on github at: link
I think there are several issues in your code.
1. First of all it is not clear why your Circle has radius, Width and Height. For a circle all 3 things should be the same. Also your render in case toFill is true looks strange. Here is a simplified version (note: I didn't compile it so there might be some bugs):
public class Circle {
public int X, Y, radius;
public Color color;
public boolean toFill;
public Circle(int x, int y, int radius, Color color, boolean fill) {
X = x;
Y = y;
this.radius = radius;
this.color = color;
toFill = fill;
}
public void render(Graphics g) {
g.setColor(color);
final int r2 = 2*radius;
if(toFill) {
g.fillOval(X, Y, r2, r2);
}
else {
for(int i=-5; i<5; i++) {
g.drawOval(X+i, Y+i, r2-i, r2-i);
}
}
}
public boolean contains(Circle pBound) {
int pBoundCenterX = pBound.X+pBound.radius;
int cirCenterX = X+radius;
int diffBetweenCentersX = Math.abs(pBoundCenterX-cirCenterX);
int pBoundCenterY = pBound.Y+pBound.radius;
int cirCenterY = Y+radius;
int diffBetweenCentersY = Math.abs(pBoundCenterY-cirCenterY);
if(diffBetweenCentersX<= (pBound.radius+radius) && diffBetweenCentersX>=Math.abs(pBound.radius-radius)) { // X
if(diffBetweenCentersY>=Math.abs(pBound.radius-radius)) { // Y
return true;
}
}
return false;
}
public int getX() {
return X;
}
public int getRadius() {
return radius;
}
public void setX(int x) {
X = x;
}
public int getY() {
return Y;
}
public void setY(int y) {
Y = y;
}
}
I didn't check your code, but I'd consider as a good practice:
renaming x and y into leftX and topY to avoid confusion with centerX/centerY meaning. Or change meaning to more typical center one.
declaring all your fields as private (see encapsulation);
declaring all your fields as final and remove all the setXyz methods (see immutability)
2. I don't understand why your createNewCircle has newR parameter and at the same time you generate a random newRadius in the first line. One of these definitely should be removed. Given that the parameter is always a constant 135 I think it should be removed.
3. Now I believe the main bug in your translation is in the lines
int newCirX = (int) newX;
int newCirY = (int) newY;
It probably should be something like
int newCirX = (int) newX - newRadius;
int newCirY = (int) newY - newRadius;
It looks like you messed with center vs top-left. Actually I think the fact that you made such a bug is an argument that supports renaming x and y I suggested in item #1.

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;
}
}

Draw lines between points, each moving in random direction

I'm working on a Java Game using LWJGL. I made a particle system and would like to obtain same result as found on this website: http://play.cubedpixels.de
This is what I got so far:
I tried my best and the problem is it's stopping and they are only moving in one direction. Also the lines are not like on this website. On the website it's smoother and better. They are using OpenGL too.
How to solve these problems and make my implementation better, more like it is one the website?
The code below shows two classes: ParticleGalaxy and Particle. Latter one is inner class of the former, but for clarity I've split them into separate snippets.
ParticleGalaxy:
public class ParticleGalaxy
{
private int count;
private int width;
private int height;
private int mousex;
private int mousey;
public ArrayList<Particle> particles = new ArrayList();
private Random random = new Random();
private TimerUtil timer = new TimerUtil();
int state = 0;
int a = 255;
int r = 255;
int g = 0;
int b = 0;
public ParticleGalaxy(int count, int width, int height)
{
this.count = count;
this.width = width;
this.height = height;
for(int i = 0; i < count; i++)
{
this.particles.add(
new Particle(this.random.nextInt(width),
this.random.nextInt(height)));
}
}
public void drawParticles(int mousex, int mousey)
{
this.mousex = mousex;
this.mousey = mousey;
for(Particle p : this.particles)
{
if(p.reset)
{
p.resetPosSize();
p.reset = false;
}
int x = Math.abs(p.getX() - mousex);
int y = Math.abs(p.getY() - mousey);
if((x < 40 && x > -40) && (y<35 && y>-40))
{
p.setConnect(true);
}
else
{
p.setConnect(false);
}
p.draw();
}
}
}
Particle:
public class Particle
{
private int x;
private int y;
private int k;
private int movey;
private int movex;
private int starty;
private int startx;
private int locationy;
private int locationx;
private float size;
private boolean reset;
private boolean connect;
private Random random = new Random();
private TimerUtil timer = new TimerUtil();
private boolean moving = false;
private boolean start = false;
public Particle(int x, int y)
{
this.x = x;
this.y = y;
this.startx = x;
this.starty = y;
this.size = genRandom(0.57F, 0.71F);
}
public void setConnect(boolean bool)
{
connect = bool;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
private void drawLine(int xto, int yto, int xfrom, int yfrom)
{
GL11.glLineWidth(1.2f);
GL11.glColor3f(1.0f, 1.0f, 1.0f);
GL11.glBegin(GL11.GL_LINE_STRIP);
GL11.glVertex2d(xto, yto);
GL11.glVertex2d(xfrom, yfrom);
GL11.glEnd();
}
public void draw()
{
if(!start)
{
start = true;
movex = height - random.nextInt(height);
movey = width - random.nextInt(width);
move(startx, starty, movex, movey);
}
float speed = 1;
float elapsed = 0.01f;
// On starting movement
float distance = (float)Math.sqrt(Math.pow(movex - startx, 2) +
Math.pow(movey - starty, 2));
float directionX = (movex - startx) / distance;
float directionY = (movey - starty) / distance;
if(moving == true)
{
x += directionX * speed * elapsed;
y += directionY * speed * elapsed;
if(Math.sqrt(Math.pow(x - startx, 2) + Math.pow(y - starty, 2)) >= distance)
{
x = (int)movex;
y = (int)movey;
resetPosSize();
this.reset = true;
moving = false;
}
}
this.k += 1;
int xx = 0;
int yy = 0;
this.locationx = this.x + xx;
this.locationy = this.y + yy;
if(locationx < 0 || locationy < 0)
this.reset = true;
if(locationx > width || locationy > height)
this.reset = true;
GuiUtils.drawCircle(this.x + xx, this.y + yy, this.size, -1);
if(connect)
{
for(Particle p : particles)
{
if(p.connect)
drawLine(locationx, locationy, p.locationx, p.locationy);
}
}
}
public void move(int startX, int startY, int endX, int endY)
{
x = (int)startX;
y = (int)startY;
moving = true;
}
public void resetPosSize()
{
this.x = this.random.nextInt(ParticleGalaxy.this.width);
this.y = this.random.nextInt(ParticleGalaxy.this.height);
startx = x;
starty = y;
movex = height - random.nextInt(height);
movey = width - random.nextInt(width);
move(startx, starty, movex, movey);
}
public float genRandom(float min, float max)
{
return (float)(min + Math.random() * (max - min + 1.0F));
}
}

How do i find Sum of values in an ArrayList (Java )? [duplicate]

This question already has answers here:
Is there possibility of sum of ArrayList without looping
(13 answers)
Closed 8 years ago.
I have an ArrayList:
ArrayList<MSS_Vector_Alg> vectors = new ArrayList<MSS_Vector_Alg>();
It will contain objects like
MSS_Vector_Alg(float x, float y, float z)
as you can see it has an (x,y,z) value. I am looking to add all the x values, y values and z values so I can get a (x-total, y-total, z-total). Is there a way I can do that?
Code ( classes for reference ):
MSS_Vector_Alg:
public class MSS_Vector_Alg {
float x;
float y;
float z;
int dimension;
String unit;
//basic ... assumes a 3D vector will be used
public MSS_Vector_Alg(){
this.x = 0;
this.y = 0;
this.z = 0;
this.dimension = 3;
this.unit = "unit";
}
//3D vector constructor
public MSS_Vector_Alg(float x, float y, float z){
this.x = x;
this.y = y;
this.z = z;
this.dimension = 3;
this.unit = "unit";
}
//2D vector constructor
public MSS_Vector_Alg (float x, float y){
this.x = x;
this.y = y;
this.dimension = 2;
this.unit = "unit";
}
//1D vector constructor
public MSS_Vector_Alg(float x){
this.x = x;
this.dimension = 1;
this.unit = "unit";
}
// getter and setters
}
MSS_Vector_Math:
public final class MSS_Vector_Math {
// a list of possible method for various vector operations
//addition
public static MSS_Vector_Alg add(ArrayList<MSS_Vector_Alg> vectors){
//TODO
return null;
}
//opposite
public static MSS_Vector_Alg opposite(MSS_Vector_Alg vector){
float tempx;
float tempy;
float tempz;
tempx = -vector.getx();
tempy = -vector.gety();
tempz = -vector.getz();
MSS_Vector_Alg rev = new MSS_Vector_Alg(tempx, tempy, tempz);
return rev;
}
//scalar multiplication
public static MSS_Vector_Alg scalarMultiply(MSS_Vector_Alg vector, float scalar){
float scax;
float scay;
float scaz;
scax = vector.getx() * scalar;
scay = vector.gety() * scalar;
scaz = vector.getz() * scalar;
MSS_Vector_Alg smul = new MSS_Vector_Alg(scax, scay, scaz);
return smul;
}
//dot multiply
public static Float dotMultiply (MSS_Vector_Alg vector1,MSS_Vector_Alg vector2 ){
float dotx;
float doty;
float dotz;
float dotmul;
dotx = vector1.getx()*vector2.getx();
doty = vector1.gety()*vector2.gety();
dotz = vector1.getz()*vector2.getz();
dotmul = dotx + doty + dotz;
return dotmul;
}
//cross multiply
public static MSS_Vector_Alg crossMultiply(MSS_Vector_Alg vector1,MSS_Vector_Alg vector2){
float x1, y1, z1, x2, y2, z2, crossx, crossy, crossz;
x1 = vector1.getx();
y1 = vector1.gety();
z1 = vector1.getz();
x2 = vector2.getx();
y2 = vector2.gety();
z2 = vector2.getz();
crossx = (y1*z2)-(z1*y2);
crossy = (z1*x2)-(x1*z2);
crossz = (x1*y2)-(y1*x2);
MSS_Vector_Alg crsmul = new MSS_Vector_Alg(crossx, crossy, crossz);
return crsmul;
}
//convert from polar to algebraic
public static MSS_Vector_Alg convertPolarToAlgebraic(MSS_Vector_Pol polarVector){
float conx, cony, conz, r;
r = polarVector.getMagnitude();
conx = ((float)r * (float)Math.cos(polarVector.getAlpha()));
cony = ((float)r * (float)Math.cos(polarVector.getBeta()));
conz = ((float)r * (float)Math.cos(polarVector.getGamma()));
MSS_Vector_Alg conv = new MSS_Vector_Alg(conx, cony, conz);
return conv;
}
//convert from algebraic to polar
public static MSS_Vector_Pol convertAlgebraicToPolar(MSS_Vector_Alg algVector){
float conx, cony, conz, r, alpha, beta, gamma;
conx = algVector.getx();
cony = algVector.gety();
conz = algVector.getz();
r = (float)Math.sqrt((conx*conx + cony*cony + conz*conz));
alpha = (float)Math.acos(conx/r);
beta = (float)Math.acos(cony/r);
gamma = (float)Math.acos(conz/r);
MSS_Vector_Pol polvec = new MSS_Vector_Pol(r, alpha, beta, gamma);
return polvec;
}
//check validity of directional angles in 3D
public static boolean checkAngles3D(float alpha, float beta, float gamma){
//TODO
return true;
}
//check validity of directional angle in 2D
public static boolean checkAngle2D(float alpha){
//TODO
return true;
}
//check validity of directional angle in 1D
public static boolean checkAngle1D(float alpha){
//TODO
return true;
}
}
Most elegant solution would probably be to use Java Stream API:
List<MSS_Vector_Alg> vectors = new ArrayList<MSS_Vector_Alg>();
float sumOfXs = (float) vectors.stream().mapToDouble(mss -> mss.x).sum();
float sumOfYs = (float) vectors.stream().mapToDouble(mss -> mss.y).sum();
float sumOfZs = (float) vectors.stream().mapToDouble(mss -> mss.z).sum();
Have you tried iterating over the list and adding those numbers?
List<MSSVectorAlg> vectors = new ArrayList<MSSVectorAlg>();
int xTotal = 0, yTotal = 0, zTotal = 0;
for (MSSVectorAlg vector : vectors)
{
xTotal += vector.getX();
yTotal += vector.getY();
zTotal += vector.getZ();
}

How can I make my image appear in a random position?

I have a chicken image that only moves whenever I press my arrow keys, the image always appear at the lower left corner when I start to run the program. My problem is that how can I make the image appear at the top or anywhere on the screen(except on the lower left) and the image still moves when I press the arrow keys . I'm not really sure but I think this problem is coming from my translate(). Is there something wrong with my calculation? Thanks for sharing your ideas...
Here's the code...
public class Chicken extends Sprite implements ImageObserver
{
private java.awt.Image fishImage;
private final Board board;
private double x;
private double y;
private final double chickenHeight = 1.6;
private final double chickenWidth = 1.8;
private double speed;
private boolean visible;
private double angle;
private double dx_m;
private double dy_m;
private boolean collision = false;
public Chicken(Board board, String name, double x, double y, double speed)
{
super(name);
this.board = board;
this.x = x;
this.y = y;
this.speed = convertToMeterPerSecond(speed);
visible = true;
URL iU = this.getClass().getResource("chicken.jpg");
ImageIcon icon = new ImageIcon(iU);
chickenImage = icon.getImage();
}
public Image getImage()
{
return chickenImage;
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
{
dx_m = -0.5;
}
if (key == KeyEvent.VK_RIGHT)
{
dx_m = 0.5;
}
if (key == KeyEvent.VK_UP)
{
dy_m = 0.5;
}
if (key == KeyEvent.VK_DOWN)
{
dy_m = -0.5;
}
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
{
dx_m = 0;
}
if (key == KeyEvent.VK_RIGHT)
{
dx_m = 0;
}
if (key == KeyEvent.VK_UP)
{
dy_m = 0;
}
if (key == KeyEvent.VK_DOWN)
{
dy_m = 0;
}
}
#Override
public void move(long dt)
{
double right_wall = board.x1_world;
double up_wall = board.y1_world;
double down_wall = 0.0;
double left_wall = 0.0;
x += dx_m;
y += dy_m;
if (x >= right_wall)
{
x = right_wall;
}
if (y > up_wall)
{
y = up_wall;
}
if (x <= left_wall)
{
x = left_wall;
}
if (y < down_wall)
{
y = down_wall;
}
}
#Override
public void render(Graphics2D g2d)
{
AffineTransform t = g2d.getTransform();
final double foot_position_y = chickenHeight;
final double foot_position_x = chickenWidth / 2;
double xx = board.convertToPixelX(x - foot_position_x);
double yy = board.convertToPixelY(y + foot_position_y);
g2d.translate(xx, yy);
// ratio for the actual size of the Image
double x_expected_pixels = chickenHeight * board.meter;
double y_expected_pixels = chickenWidth * board.meter;
double w = ((ToolkitImage) chickenImage).getWidth();
double h = ((ToolkitImage) chickenImage).getHeight();
double x_s = x_expected_pixels / w;
double y_s = y_expected_pixels / h;
g2d.scale(x_s, y_s);
g2d.drawImage(getImage(), (int) x, (int) y, this);
g2d.setTransform(t);
}
#Override
public void moveAt(double distance_x, double distance_y)
{
this.x = (int) distance_x;
this.y = (int) distance_y;
}
public void setAngle(double angle)
{
this.angle = angle;
}
#Override
public RectangleX getBounds()
{
return new RectangleX(x, y, chickenWidth, chickenHeight);
}
#Override
public double getWidth()
{
return WIDTH;
}
#Override
public double getHeight()
{
return HEIGHT;
}
#Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
{
return true;
}
}
this is my chicken class
public double meter;
int y1_pixel;
y1_pixel = getHeight();
public int convertToPixelX(double distance)
{
return (int) (distance * meter);
}
public int convertToPixelY(double y_world)
{
return (int) (y1_pixel - (y_world * meter));
}
this is coming from my board class.
Your render method is using the x and y coordinates of the class to determine where to draw the Chicken each time. A simple solution to your problem is to use random values for x and y when you create a Chicken instance.
An alternate solution would be to create another constructor that do not take values for x or y and instead sets them to be default values anywhere between 0 and board.x1_world or board.y1_world, depending on the variable.
public Chicken(Board board, String name, double speed)
{
this( board, name,
(int)( Math.random() * ( board.x1_world - chickenWidth ) ),
(int)( Math.random() * ( board.y1_world - chickenHeight ) ),
speed );
}

Categories

Resources