mass change values of arraylist - java

I have array list of circles, whitch are drawing by canvas. And everything is OK. But I need change all X,Y coordinates of circles, by during the program.
static ArrayList<Circle> mCircles;
private static void createCircles() {
if (mCircles == null) {
mCircles = new ArrayList<Circle>();
}
int rana = 66/(koeficient);
mCircles.add(new Circle(80, 200, rana));
}
public static void AddCircle() {
int rana = 66/(koeficient);
mCircles.add(new Circle(80, 200, rana));
}
private void Drawing(Canvas canvas) {
for (Circle c : mCircles) {
canvas.drawCircle(c.getCurrentX(), c.getCurrentY(), c.getRadius(),
mMalovani);
}
}
public static Circle findCircleClosestToTouchEvent(float x, float y) {
Circle c = mCircles.get(mCircles.size() - 1);
return c;
}
public class Circle extends Shape {
final float mRadius;
public Circle(float x, float y, float r) {
super(x, y);
mRadius = r;
}
final float getRadius() {
return mRadius;
}
}
public class Shape extends Activity {
protected float mStartX = 0f;
protected float mStartY = 0f;
public float mCurrentX = 30f;
public float mCurrentY = 30f;
protected float mActionDownX;
protected float mActionDownY;
protected float mActionMoveOffsetX;
protected float mActionMoveOffsetY;
// x y coordinate of a move action
public Shape (float x, float y) {
mStartX = x;
mStartY = y;
mCurrentX = x;
mCurrentY = y;
}
public void setStartX(float x) { mStartX = x; }
public void setStartY(float y) { mStartY = y; }
public float getCurrentX() { return mCurrentX; }
public float getCurrentY() { return mCurrentY; }
public void setCurrentX(float x) { mCurrentX = x;
}
public void setCurrentY(float y) { mCurrentY = y; }
public void setActionMoveOffsetX(float x) { mActionMoveOffsetX = x; }
public void setActionMoveOffsetY(float y) { mActionMoveOffsetY = y; }
public float getActionMoveOffsetX() { return mActionMoveOffsetX; }
public float getActionMoveOffsetY() { return mActionMoveOffsetY; }
public void setActionDownX(float x) { mActionDownX = x; }
public void setActionDownY(float y) { mActionDownY = y; }
public float getActionDownX() { return mActionDownX; }
public float getActionDownY() { return mActionDownY; }
public void restoreStartPosition() {
mCurrentX = mStartX;
mCurrentY = mStartY;
}
}

Assuming you have setCurrentX and setCurrentY methods opposite the getter methods, just loop through the list of circles.
private void changeCoordinates(List<Circle> circles, int x, int y){
for(Circle c:circles){
c.setCurrentX(x);
c.setCurrentY(y);
}
}

Related

Calculating the distance between a line segment and a point

I am currently developing a tower defense game in java from scratch and I am reworking the bullet collisions. for this I need to calculate the distance between a given point and a line segment. I have already written a function to do just that, but it does often give the distance from one of the points when it is not supposed to.
the line segment class:
public class LineSegment {
public Vector2DK p;
public Vector2DK q;
/**
* Creates a line segment between the points P and Q
* #param p Point P
* #param q Point Q
*/
public LineSegment(Vector2DK p, Vector2DK q) {
this.p = p;
this.q = q;
}
/**
* Calculates the distance to point R
* #param r Point R
* #return Distance
*/
public double distanceFrom(Vector2DK r) {
// after trying what feels like everything I might have gotten a little confused(stupid errors ahead)
Vector2DP differenceVector = r.subtract(p).toPolar();
Vector2DP differenceVector2 = r.subtract(q).toPolar();
double alpha = differenceVector.getAngle() - q.subtract(p).getAngle();
double beta = differenceVector2.getAngle() - q.subtract(p).getAngle();
if (alpha < Math.PI / 2 && alpha > -Math.PI / 2) {
return p.distanceTo(r);
} else if (beta > Math.PI / 2 || beta < -Math.PI / 2) {
return q.distanceTo(r);
}
return Math.abs(differenceVector.getMagnitude() * Math.sin(alpha));
}
public static void main(String[] args) {
// a main method for testing
// I already added a case where the bullet of the tower flew right thru the enemy(but I probably got the wrong tick, so the values are probably not good for testing)
Vector2DK linePoint0 = new Vector2DK(339.9354152826523, 374.7835775987438);
Vector2DK linePoint1 = new Vector2DK(317.79869321314067, 388.4287303893724);
Vector2DK point = new Vector2DK(290.0194200000002, 400.0);
LineSegment lineSegment = new LineSegment(linePoint0, linePoint1);
Line line = new Line(linePoint0, linePoint1);
System.out.println(lineSegment.distanceFrom(point));
}
}
my two vector classes:
public class Vector2DK implements Vector2D {
private double x;
private double y;
public Vector2DK(double x, double y) {
this.x = x;
this.y = y;
}
public Vector2DK(Vector2D vector) {
Vector2DK vector2DK = vector.toKartesian();
x = vector2DK.x;
y = vector2DK.y;
}
public void copyToSelf(Vector2DK vector) {
x = vector.x;
y = vector.y;
}
#Override
public String toString() {
return String.format("Vector2DK(%s, %s)", x, y);
}
#Override
public Vector2DK toKartesian() {
return new Vector2DK(x, y);
}
#Override
public Vector2DP toPolar() {
return new Vector2DP(getMagnitude(), getAngle());
}
#Override
public double getAngle() {
return Math.atan2(y, x);
}
#Override
public double getMagnitude() {
return Math.sqrt(getMagnitudeSquare());
}
#Override
public double getX() {
return x;
}
#Override
public double getY() {
return y;
}
#Override
public void setAngle(double angle) {
Vector2DP vector = toPolar();
vector.setAngle(angle);
copyToSelf(vector.toKartesian());
}
#Override
public void setMagnitude(double magnitude) {
Vector2DP vector = toPolar();
vector.setAngle(magnitude);
copyToSelf(vector.toKartesian());
}
#Override
public void setX(double x) {
this.x = x;
}
#Override
public void setY(double y) {
this.y = y;
}
#Override
public double getMagnitudeSquare() {
return x * x + y * y;
}
#Override
public double distanceTo(Vector2D vector) {
return Math.sqrt(MathFunc.square(x - vector.getX()) + MathFunc.square(y - vector.getY()));
}
#Override
public void normalize() {
double magnitude = getMagnitude();
x /= magnitude;
y /= magnitude;
}
#Override
public void reverse() {
x = -x;
y = -y;
}
#Override
public Vector2D add(Vector2D vector) {
return new Vector2DK(x + vector.getX(), y + vector.getY());
}
#Override
public Vector2D subtract(Vector2D vector) {
return new Vector2DK(x - vector.getX(), y - vector.getY());
}
#Override
public Vector2D scale(double value) {
return new Vector2DK(x * value, y * value);
}
#Override
public void addWith(Vector2D vector) {
x += vector.getX();
y += vector.getY();
}
#Override
public void subtractWith(Vector2D vector) {
x -= vector.getX();
y -= vector.getY();
}
#Override
public void scaleWith(double value) {
x *= value;
y *= value;
}
#Override
public double dotProduct(Vector2D vector) {
return x * vector.getX() + y * vector.getY();
}
}
and:
public class Vector2DP implements Vector2D {
private double magnitude;
private double angle;
public Vector2DP(double magnitude, double angle) {
this.magnitude = magnitude;
this.angle = angle;
}
public Vector2DP(Vector2DP vector) {
Vector2DP vector2DP = vector.toPolar();
this.magnitude = vector.magnitude;
this.angle = vector.angle;
}
public void copyToSelf(Vector2DP vector) {
magnitude = vector.magnitude;
angle = vector.angle;
}
#Override
public String toString() {
return String.format("Vector2DP(%su, %s°)", magnitude, Math.toDegrees(angle));
}
#Override
public Vector2DK toKartesian() {
return new Vector2DK(getX(), getY());
}
#Override
public Vector2DP toPolar() {
return new Vector2DP(magnitude, angle);
}
#Override
public double getAngle() {
return angle;
}
#Override
public double getMagnitude() {
return magnitude;
}
#Override
public double getX() {
return Math.cos(angle) * magnitude;
}
#Override
public double getY() {
return Math.sin(angle) * magnitude;
}
#Override
public void setAngle(double angle) {
this.angle = angle;
}
#Override
public void setMagnitude(double magnitude) {
this.magnitude = magnitude;
}
#Override
public void setX(double x) {
Vector2DK vector = toKartesian();
vector.setX(x);
copyToSelf(vector.toPolar());
}
#Override
public void setY(double y) {
Vector2DK vector = toKartesian();
vector.setY(y);
copyToSelf(vector.toPolar());
}
#Override
public double getMagnitudeSquare() {
return magnitude * magnitude;
}
#Override
public double distanceTo(Vector2D vector) {
return subtract(vector).getAngle();
}
#Override
public void normalize() {
magnitude = 1;
}
#Override
public void reverse() {
angle += angle < Math.PI ? Math.PI : -Math.PI;
}
#Override
public Vector2D add(Vector2D vector) {
return toKartesian().add(vector).toPolar();
}
#Override
public Vector2D subtract(Vector2D vector) {
return toKartesian().add(vector).toPolar();
}
#Override
public Vector2D scale(double value) {
return new Vector2DP(magnitude * value, angle);
}
#Override
public void addWith(Vector2D vector) {
copyToSelf((Vector2DP) add(vector));
}
#Override
public void subtractWith(Vector2D vector) {
copyToSelf((Vector2DP) subtract(vector));
}
#Override
public void scaleWith(double value) {
magnitude *= value;
}
#Override
public double dotProduct(Vector2D vector) {
Vector2DP vector2DP = vector.toPolar();
return magnitude * vector2DP.magnitude * Math.cos(angle - vector2DP.angle);
}
}
Consider the next Python code (hope it is easy to translate it).
At first function check dot products of segment vector and vectors from the start and end of segment to the point.
If projection of point onto the line lies outside the segment, sign of dot product reveals this fact, and we return distance to the closest segment end (points A,B,C,D at the picture)
Otherwise we return length of projection (formula from wiki) (point E at the picture)
hypot gives vector length (like your getMagnitude)
import math
def pt_seg_dist(px, py, qx, qy, rx, ry):
qpx = qx - px
qpy = qy - py
rpx = rx - px
rpy = ry - py
if rpx * qpx + rpy * qpy <= 0:
return math.hypot(rpx, rpy)
rqx = rx - qx
rqy = ry - qy
if rqx * qpx + rqy * qpy >= 0:
return math.hypot(rqx, rqy)
return abs(rpx * qpy - rpy * qpx) / math.hypot(qpx, qpy)
print(pt_seg_dist(0, 0, 1, 0, 0.5, 2))
print(pt_seg_dist(0, 0, 1, 0, -2, 2))
print(pt_seg_dist(0, 0, 1, 0, 3, -2))
>>>
2.0
2.8284271247461903
2.8284271247461903

Collision Detection Glitches

Thanks in advance. I am trying to make a scrolling 2d game with perfect collision detections on the corners of the player. The problem I am having is that if you go left or down on a wall, it works just fine, but on the right or up, it seems to infinitely detect collisions and glitch you to a corner.
I have tried resetting the motion, reverting to old location, subtracting pixels from the position after the translation, and also changing the variables.
package me.Rigidity.Apocalypse;
public class Entity extends Tile {
private float x, y, xm, ym;
public Entity(String name, float r, float g, float b, float x, float y, float size) {
super(name, r, g, b);
this.size = size;
this.x = x;
this.y = y;
}
public void move(float x, float y) {
this.x += x;
this.y += y;
}
public void position(float x, float y) {
this.x = x;
this.y = y;
}
public void factor(float x, float y) {
this.xm *= x;
this.ym *= y;
}
public void motion(Map map) {
motionX(map);
motionY(map);
}
public void motionX(Map map) {
x += xm;
if (collision(map)) {
if (left(map)) {
x = rightX();
}
if (right(map)) {
x = leftX();
}
}
}
public void motionY(Map map) {
y += ym;
if (collision(map)) {
if (top(map)) {
y = bottomY();
return;
}
if (bottom(map)) {
y = topY();
}
}
}
public void motion(float x, float y) {
xm += x;
ym += y;
}
public float x() {
return x;
}
public float y() {
return y;
}
public void x(float x) {
this.x = x;
}
public void y(float y) {
this.y = y;
}
public float xm() {
return xm;
}
public float ym() {
return ym;
}
public Tile bottomleft(Map map) {
return map.getAbsoluteTile(leftX(), bottomY());
}
public Tile bottomright(Map map) {
return map.getAbsoluteTile(rightX(), bottomY());
}
public Tile topleft(Map map) {
return map.getAbsoluteTile(leftX(), topY());
}
public Tile topright(Map map) {
return map.getAbsoluteTile(rightX(), topY());
}
public int leftX() {
return (int)(((int)(x/Tile.BASIC.size()))*Tile.BASIC.size()+Tile.BASIC.size()-size);
}
public int rightX() {
return (int)(((int)(x/Tile.BASIC.size()))*Tile.BASIC.size()+Tile.BASIC.size());
}
public int topY() {
return (int)(((int)(y/Tile.BASIC.size()))*Tile.BASIC.size()+Tile.BASIC.size());
}
public int bottomY() {
return (int)(((int)(y/Tile.BASIC.size()))*Tile.BASIC.size()+Tile.BASIC.size()-size);
}
public boolean top(Map map) {
return topleft(map) instanceof Solid || topright(map) instanceof Solid;
}
public boolean bottom(Map map) {
return bottomleft(map) instanceof Solid || bottomright(map) instanceof Solid;
}
public boolean left(Map map) {
return topleft(map) instanceof Solid || bottomleft(map) instanceof Solid;
}
public boolean right(Map map) {
return topright(map) instanceof Solid || bottomright(map) instanceof Solid;
}
public boolean collision(Map map) {
return bottomleft(map) instanceof Solid || topleft(map) instanceof Solid || bottomright(map) instanceof Solid || topright(map) instanceof Solid;
}
}
There is no error message, however the result isn't as expected on the right or top collision. Left and bottom work as expected with clean collision, as well as the sliding motion.

Trying To Implement Player Gravity For My Test Block for Player Class (RealtutsGml Platformer Tutorial)

I am following realTutsgml Tutorial in attempt to implement gravity for the player class which I am using a Linklist to refer to my Gameobject class.
public class Player extends GameObject {
private float width = 32, height = 64;
private float gravity = 0.05f;
public Player(float x, float y, ObjectId id) {
super(x, y, id);
}
public void tick(LinkedList<GameObject> object) {
x += velX;
y += velY;
if(falling||jumping)
{
velY += gravity;
}
}
I was able to draw the test block onto the screen which an instance was created in the game class in the init method
handler.addObject(new Player(100, 100, ObjectId.Player));
GameObject Class
public abstract class GameObject
{
protected float x, y;
protected ObjectId id;
protected float velX = 0, velY = 0;
protected boolean falling = true;
protected boolean jumping = false;
public GameObject(float x, float y, ObjectId id)
{
this.x = x;
this.y = y;
this.id = id;
}
public abstract void tick(LinkedList<GameObject> object);
public abstract void render(Graphics g);
public abstract Rectangle getBounds();
public float getX() {
return x;
}
public float getY() {
return y;
}
public void setX(float x) {
this.x = x;
}
public void setY(float y) {
this.y = y;
}
public float getvelX() {
return velX;
}
public float getvelY() {
return velY;
}
public void setvelX(float velX) {
this.velX = velX;
}
public void setvelY(float velY) {
this.velY = velY;
}
public boolean isFalling() {
return falling;
}
public void setFalling(boolean falling) {
this.falling = falling;
}
public boolean isJumping() {
return jumping;
}
public void setJumping(boolean jumping) {
this.jumping = jumping;
}
public ObjectId getId() {
return id;
}
}
I added the getters and setters to generate the return value for the jumping and falling boolean values.

LWJGL glTranslatef not rendering depth

I am render a square with in 3D space. When I use the glTranslatef() method and add a z coordinate the square is no longer visible. When the z coordinate is above 1 or below -1 then square is no longer displayed (I tested it by setting the z coordinate to 1. If and it didn't display).
Main.java
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
initDisplay();
gameLoop();
cleanUp();
}
public static void initDisplay(){
try {
Display.setDisplayMode(new DisplayMode(800, 600));
Display.setTitle("AWESOMENESS!");
Display.create();
} catch (LWJGLException e) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
}
}
public static void gameLoop(){
Camera cam = new Camera(70, (float)Display.getWidth() / (float)Display.getHeight(), 0.3f, 1000);
while(!Display.isCloseRequested()){
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
cam.useView();
glPushMatrix();{
glColor3f(1.0f, 0.5f, 0f);
//This is the problematic line. When the 3rd param goes above 1 or below -1 the
//square disappers.
glTranslatef(0,0,-10);
glBegin(GL_QUADS);{
glVertex3f(0,0,0);
glVertex3f(0,1,0);
glVertex3f(1,1,0);
glVertex3f(1,0,0);
}
glEnd();
}
glPopMatrix();
Display.update();
}
}
public static void cleanUp(){
Display.destroy();
}
}
Camera.java
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.util.glu.GLU.*;
public class Camera {
//Position
private float x;
private float y;
private float z;
//Rotation
private float rx;
private float ry;
private float rz;
private float fov;
private float aspect;
private float near;
private float far;
public Camera(float fov, float aspect, float near, float far) {
x = 0;
y = 0;
z = 0;
rx = 0;
ry = 0;
rz = 0;
this.fov = fov;
this.aspect = aspect;
this.near = near;
this.far = far;
initProjection();
}
private void initProjection(){
glMatrixMode(GL_PROJECTION_MATRIX);
glLoadIdentity();
gluPerspective(fov, aspect, near, far);
glMatrixMode(GL_MODELVIEW);
}
public void useView(){
glRotatef(rx, 1, 0, 0);
glRotatef(ry, 0, 1, 0);
glRotatef(rz, 0, 0, 1);
glTranslatef(x, y, z);
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public float getZ() {
return z;
}
public float getRx() {
return rx;
}
public float getRy() {
return ry;
}
public float getRz() {
return rz;
}
public float getFov() {
return fov;
}
public float getAspect() {
return aspect;
}
public float getNear() {
return near;
}
public float getFar() {
return far;
}
public void setX(float x) {
this.x = x;
}
public void setY(float y) {
this.y = y;
}
public void setZ(float z) {
this.z = z;
}
public void setRx(float rx) {
this.rx = rx;
}
public void setRy(float ry) {
this.ry = ry;
}
public void setRz(float rz) {
this.rz = rz;
}
public void setFov(float fov) {
this.fov = fov;
}
public void setAspect(float aspect) {
this.aspect = aspect;
}
public void setNear(float near) {
this.near = near;
}
public void setFar(float far) {
this.far = far;
}
}
glMatrixMode(GL_PROJECTION_MATRIX);
Instead should be:
glMatrixMode(GL_PROJECTION);
GL_PROJECTION_MATRIX does not render the 3rd dimension. There is no further documentation on this matter.

How to handle the collision between two arraylist objects?

I have a problem with my code here. I want to make a game with thow ball on each side of screen, on ball being controlled by the user and the other one by the computer. Both ball shoot to each other, and if the bullets intersects one with another, i need to make something happen. I managed to do some thing here, and I have two class, one for the player bullets, and the other one for the enemies bullets, and the bullets are created trough arraylists. All works fin until now, but if I try ti make them collision with each other,it doesnt work at all. I've tried a lot of things but none of it worked, and I would really appreciate if someone could help me.
That is the Player Projectile class:
import java.awt.Rectangle;
public class Projectiles {
private int x, y, speedX;
private boolean visible;
private int width = 10;
private int height = 10;
private Rectangle r;
public Projectiles(){
}
public Projectiles(int startX, int startY) {
x = startX;
y = startY;
speedX = 1;
visible = true;
r = new Rectangle(0, 0, 0, 0);
}
public void update(){
x += speedX;
r.setBounds(x, y, width, height);
if (x > 800){
visible = false;
r = null;
}
if (x < 800){
checkCollision();
}
}
private void checkCollision() {
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getSpeedX() {
return speedX;
}
public boolean isVisible() {
return visible;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setSpeedX(int speedX) {
this.speedX = speedX;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public Rectangle getR() {
return r;
}
public void setR(Rectangle r) {
this.r = r;
}
}
And this one is the Enemy_Projectile class:
import java.awt.Rectangle;
public class Enemy_Projectiles {
private int x, y, speedX;
private boolean visible;
private int width = 30;
private int height = 20;
public static Rectangle r;
Projectiles p1;
public Enemy_Projectiles(int startX, int startY) {
x = startX;
y = startY;
speedX = 1;
visible = true;
r = new Rectangle(0, 0, 0, 0);
}
public void update() {
x -= speedX;
r.setBounds(x, y, width, height);
if (x < 0) {
visible = false;
r = null;
}
if (x > 0){
checkCollision();
}
}
private void checkCollision() {
if(r.intersects(p1.getR())){
visible = false;
System.out.println("Coliziune!!");
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getSpeedX() {
return speedX;
}
public boolean isVisible() {
return visible;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setSpeedX(int speedX) {
this.speedX = speedX;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
}
Do not check intersection after the frame has been drawn. Let's say you have a slow computer and your bullets intersect, but they have moved out of intersection in one frame.
You need to apply high school physics/geometry. Calculate where the bullet will be well before you render it. Then, calculate where the ball will be, and construct a line segment for each from where they are now, to where they will be on the next frame. Check if these segments intersect. Then you will have a fool-proof method of checking for intersection.
This method is similar to how physics and intersections between objects are handled inside of a game engine like Unity.

Categories

Resources