I've been trying to get an enemy's coordinates so I can act on where they are. The code I use does not seem to work:
double absBearing = e.getBearingRadians() + e.getHeadingRadians();
double ex = getX() + e.getDistance() * Math.sin(absBearing);
double ey = getY() + e.getDistance() * Math.cos(absBearing);
I seem to be getting odd returns that are giving me values greater than the size of the field and even minus numbers, has anyone any idea on how to ammend this piece of code to get the enemy's X and Y in the same way my X and Y is returned?
public class MyRobot extends AdvancedRobot {
private RobotStatus robotStatus;
(...)
public void onStatus(StatusEvent e) {
this.robotStatus = e.getStatus());
}
public void onScannedRobot(ScannedRobotEvent e) {
double angleToEnemy = e.getBearing();
// Calculate the angle to the scanned robot
double angle = Math.toRadians((robotStatus.getHeading() + angleToEnemy % 360);
// Calculate the coordinates of the robot
double enemyX = (robotStatus.getX() + Math.sin(angle) * e.getDistance());
double enemyY = (robotStatus.getY() + Math.cos(angle) * e.getDistance());
}
(...)
}
Related
I want to create a "spiral effect" with particles (or any entities) in Java.
I'm new to objective programming (and also Java), so I started with something easier. I firstly created a Path object that has a value of Locations[] signed to it, it gets from the user a: Start location, End location, and double value, that tells him, how much space between each location in the path he has.
private void setLocations() {
//initialize vars
Location start = getStart();
World world = start.getWorld();
Location[] locations = new Location[amount];
double x = start.getX();
double y = start.getY();
double z = start.getZ();
//loop that will set values for locations
for (int i = 0; i < amount; i++) {
locations[i] = new Location(
world,
x + dividedDistanceX * (i + 1),
y + dividedDistanceY * (i + 1),
z + dividedDistanceZ * (i + 1)
);
}
this.locations = locations;
}
Now you might be asking what is the amount? So simply it's the number of points that are created when the object is initialized. It's simple math like getting the longest distance from point to point, and then dividing it by the value of space between each point.
Now the situation gets a little more complicated, so I prepared graphics for you:)
I want to rotate points around the longest axis to form some form of a spiral, and I want from user to set the maximum distance between the starting point and the new one.
Something like this:
And another graph of the sinusoid around one vector (x, y)
Honestly, I need some help.
Here's GitHub object link
Things I know I need to do:
Get the axis around which I will rotate point (it's the longest distance between points)
Add some value to the rest values (x+something, y+something)
Add angle, that point will rotate with, (for example each point will be rotated by 22,5).
Okay, so i did it, it wasn't even that hard:
public Location[] createSpiral(double radius, float angle, Location[] path) {
final int length = path.length;
Location[] result = path.clone();
Location start = path[0];
Location end = path[length - 1];
double startX = start.getX();
double startY = start.getY();
double startZ = start.getZ();
double endX = end.getX();
double endY = end.getY();
double endZ = end.getZ();
double distanceX = setDistance(startX, endX);
double distanceY = setDistance(startY, endY);
double distanceZ = setDistance(startZ, endZ);
double highestOffset = getHighestOffset(new double[]{distanceX, distanceY, distanceZ});
if (highestOffset == abs(distanceX)) {
for (int i = 0; i < length; i++) {
double sin = radius * sin(angle * i / length);
double cos = radius * cos(angle * i / length);
result[i].setY(result[i].getY() + cos);
result[i].setZ(result[i].getZ() + sin);
}
} else if (highestOffset == abs(distanceY)) {
for (int i = 0; i < length; i++) {
double sin = radius * sin(angle * i / length);
double cos = radius * cos(angle * i / length);
result[i].setX(result[i].getX() + cos);
result[i].setZ(result[i].getZ() + sin);
}
} else if (highestOffset == abs(distanceZ)) {
for (int i = 0; i < length; i++) {
double sin = radius * sin(angle * i / length);
double cos = radius * cos(angle * i / length);
result[i].setX(result[i].getX() + cos);
result[i].setY(result[i].getY() + sin);
}
} else {
return path;
}
return result;
}
It's just
double sin = radius * sin(angle * i / length);
double cos = radius * cos(angle * i / length);
and adding those values to corresponding X, Y if Z has the highest distance from a location, etc.
The rest of the code and methods are located in the GitHub link above.
In celebration of Pi Day, I decided to implement the Monte Carlo method to approximate the value of π, but my algorithm doesn’t seem to be working.
I've tried running with different parameters, but I always get approx 3.66
I've tried debugging but I can't figure it out.
public class ApproximatePi {
private int iterations; // how many points to test
private double r; // width of the square / radius of circle (quarter circle)
private int inCount = 0; // number of points that are inside the circle
private int outCount = 0; // number of points outside of the circle
private Random getNum = new Random(System.currentTimeMillis());
ApproximatePi(int iterations, double r) {
this.iterations = iterations;
this.r = r;
// getNum = new Random(System.currentTimeMillis());
}
public double getApproximation() {
for (int i = 0; i < iterations; i++) {
double x = (r) * getNum.nextDouble();
double y = (r) * getNum.nextDouble();
if (inside(x, y)) {
inCount++;
} else
outCount++;
}
double answer = (double) inCount / (double) outCount;
return answer;
}
private boolean inside(double x, double y) {
// if the hypotenuse is greater than the radius, the point is outside the circle
if (getHypot(x, y) >= r) {
return false;
} else
return true;
}
private double getHypot(double x, double y) {
double s1 = Math.pow(x, 2);
double s2 = Math.pow(y, 2);
return Math.sqrt(s1 + s2);
}
}
So, lets assume that radius is 1, so in this case what actually you're doing:
Generate bunch of x,y coordinates within square with coordinates (0,0) - (1,1)
Then you test which of them are within circle with center at (0,0)
By counting in/out counters you're getting how many points within circle's segment and how many outside
inCount / (inCount+outCount) represents ratio between in points to total surface
r² is total surface
Thus, you can get approximate area of 1/4th of circle via formula inCount / (inCount+outCount) * r² == pi * r² / 4
Now, you can say that 4 * inCount / (inCount+outCount) == pi
I'm trying to write a program that checks if a circle contains another circle, if a certain point is inside a circle, or the one I'm having trouble with, if a circle overlaps with another circle.
import javafx.scene.shape.Circle;
public class Problem10_11 {
public static void main(String[] args) {
//Create circle with certain parameters.
Circle2D c1 = new Circle2D(2, 2, 5.5);
//Create output which will be tested by all our methods.
System.out.println("The area for circle 1 is " +c1.getArea()+
" and its perimeter is " + c1.getPerimeter());
System.out.println("Is (3,3) contained within circle 1? "
+ c1.contains(3, 3));
System.out.println("Does circle 1 contain circle 2? "
+ c1.contains(new Circle2D(4,5,10.5)));
System.out.println("Does circle 1 overlap with circle 3? "
+ c1.overlaps(new Circle2D(3, 5, 2.3)));
}
}
class Circle2D {
double x; //first parameter
double y; //second parameter
double radius; //third parameter
Circle2D() {
}
public Circle2D(double x, double y, double radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
public void setX(double x) {
this.x = x; //set x
}
public double getX() {
return x; //grab x
}
public void setY(double y) {
this.y = y; //set y
}
public double getY() {
return y; //grab y
}
public void setRadius(double radius) {
this.radius = radius; //set radius
}
public double getRadius() {
return radius; //grab radius
}
public double getArea() {
double area = Math.PI*radius*radius; //formula for area
return area;
}
public double getPerimeter() {
double perimeter = 2*Math.PI*radius; //formula for perimeter
return perimeter;
}
public boolean contains(double x, double y) {
//Use distance formula to check if a specific point is within our circle.
double distance = Math.sqrt(Math.pow(this.x - x, 2) + (Math.pow(this.y - y, 2)));
if (distance <= radius * 2)
return true;
else {
return false;
}
}
public boolean contains(Circle2D circle) {
//Use distance formula to check if a circle is contained within another circle.
double distance = Math.sqrt(Math.pow(circle.getX() - x, 2) + (Math.pow(circle.getY() - y, 2)));
if (distance <= (this.radius - circle.radius)) {
return true;
} else {
return false;
}
}
public boolean overlaps(Circle2D circle) {
//Use distance formula to check if a circle overlaps with another circle.
double distance = Math.sqrt(Math.pow(circle.getX() - x, 2) + (Math.pow(circle.getY() - y, 2)));
}
}
So my overlap method is all the way at the bottom but I don't really have anything inside because I'm not sure exactly what to do. I tried this :
if (distance <= radius) return true;
else return false;
but that didnt work. So I'm not sure what else to try. FYI, I'm trying to check if c1 overlaps with a circle with parameters (3, 5, 2.3). I appreciate any suggestions/advice.
You can refer to Relative position of two circles.
public boolean overlaps(Circle2D circle) {
//Use distance formula to check if a circle overlaps with another circle.
double distance = Math.sqrt(Math.pow(circle.getX() - x, 2) + (Math.pow(circle.getY() - y, 2)));
return distance <= (this.radius + circle.radius) and distance >= Math.abs(this.radius - circle.radius)
}
if the distance between the centres of the circles is less than the sum of the radius of the two circles then they are overlapping.
double minDistance = Math.max(circle.getRadius(),this.radius) - Math.min(circle.getRadius(),this.radius);
if (distance <= (this.radius + circle.getRadius()) && distance>= minDistance) return true;
else return false;
1.- you have to to place both circles in space, give them some cordinates
2.- you have to get the vectors from 2 circles.
3.- you have to normailze those vectors and get the correct distance in units,
im gonna use pixels.
4.- finally you have to check if the distance between those 2 vectors are less that the radious of both circles, if so, then they are overlaped.
here you have a link that is better explained:
https://gamedevelopment.tutsplus.com/tutorials/when-worlds-collide-simulating-circle-circle-collisions--gamedev-769, actually this is something very common we use in game development when we want to check circle collisions ( for 2D games )
Most answers here are wrong.
There are three cases to consider:
Circles overlap and the center of the smaller circle is inside the bigger circle
Circles overlap and the center of the smaller circle is outside the bigger circle
3.
The two circles touch at their borders
The algorithm is this (in Java):
Calculate the distance between centers:
double centersDistance = Math.sqrt((x2 - x1)^2 + (y2 - y1)^2)
Check if one circle contains another:
boolean blueContainsRed = blue.radius > centersDistance + red.radius;
boolean redContainsBlue = red.radius > centersDistance + blue.radius;
Check if they overlap:
boolean circlesOverlap = centersDistance <= blue.radius + red.radius;
the <= would make sure that true is returned for case 3 (when borders only touch). If you don't want that, use < .
So the final formula would be:
return !blueContainsRed && !redContainsBlue && circlesOverlap;
This table might also prove useful (from https://planetcalc.com/8098/):
public class Pond {
public static void allcreationco(){
for (int i = 0; i < 100; i++){
int radius = 100;
int x = (int) (Math.random() * 2 * radius - radius);
int ylim = (int) Math.sqrt(radius * radius - x * x);
int y = (int) (Math.random() * 2 * ylim - ylim);
Fish.xfishc.add((int) x);
Fish.yfishc.add((int) y);
}
allcreationdir();
}
public static void allcreationdir(){
for (int i = 0; i < Fish.xfishc.size(); i++){
double radius = Math.random()*1;
double angle = Math.random()*2*Math.PI;
double x = Math.cos(angle)*radius + 0;
if (x > 0){
Fish.xfishcb1.add(true);
}
else {
Fish.xfishcb1.add(false);
}
}
for (int i = 0; i < Fish.yfishc.size(); i++){
double radius = Math.random()*1;
double angle = Math.random()*2*Math.PI;
double x = Math.cos(angle)*radius + 0;
if (x > 0){
Fish.yfishcb1.add(true);
}
else {
Fish.yfishcb1.add(false);
}
}
Hi, my objective is to create a simulation (no visual drawing needed, just something to easily print info about) of a circular pond with fish randomly swimming in it. The code above is a way of initiating 100 hypothetical fish into Arraylists in the form of x and y coordinates based on a hypothetical circle with a radius of 100 (there's gotta be a better way to do this). I would like to have each of the 100 fish be able to swim in random directions and change to new random directions every time they reach the end of the pond. Maybe I'd like them to reproduce after a certain time, or include another fish that moves in straight lines and can eat another fish.
public class Salmon extends Fish {
public static int salmonre = 0;
public static void salmonmove(){
for (int i = 0; i < xfishc.size(); i++){
if (xfishcb1.get(i) == true){
int d = xfishc.get(i);
int e = d + 1;
xfishc.set(i , e);
}
else{
int d = xfishc.get(i);
int e = d - 1;
xfishc.set(i , e);
}
}
for (int i = 0; i < yfishc.size(); i++){
if (yfishcb1.get(i) == true){
int d = yfishc.get(i);
int e = d + 1;
yfishc.set(i , e);
}
else{
int d = yfishc.get(i);
int e = d - 1;
yfishc.set(i , e);
}
}
salmonre++;
}
}
I also used Boolean arraylists to randomly determine what directions the fish are supposed move in. Please be gentle with me in your rhetoric because I'm well aware that my approaches are ridiculous. I know it's best to use trigonometry when simulating objects and their behaviors in a circle, but for some reason, I'm not able to wrap my head around this when looking on the internet (I keep finding things more complicated that involve visual illustrations). Could you "please" give me comprehensive answers with ideas? I'm frustrated.
I wasn't entirely able to figure out how you wanted your Fish class to work based on your code, but some tips:
In Object Oriented programming, you do not want to have a class Fish that has static methods for updating two lists containing X and Y coordinates for all the fish.
Instead, you want an object of class Fish to represent everything about a single fish. You can then have a list of Fish objects.
A pair of booleans is really too coarse for directions. Use a double instead, one for each fish (stored in the Fish instance).
To implement the direction changing behavior, just check whether the next move would move the fish out of the water, and if so, pick a different direction.
Here's a simple, self contained example of the above for two Fish. They start out together and in the same direction, but diverge when they hit the edge and swim in different, random directions:
class Fish {
private double x, y;
private double angle, speed;
public Fish() {
x = y = angle = 0;
speed = 5;
}
void move() {
// If we swim at this angle, this is where we'll end up
double newX = x + Math.cos(angle) * speed;
double newY = y + Math.sin(angle) * speed;
if (isInPond(newX, newY)) {
// That's still in the pond, go there
x = newX;
y = newY;
} else {
// That's outside the pond, change direction
angle = Math.random() * 2 * Math.PI;
}
}
public String toString() {
return String.format(
"Position: %.0f,%.0f. Angle: %.0f degrees.",
x, y, angle * 180/Math.PI);
}
// Check whether some coordinates are within a circular pond with radius 100
static boolean isInPond(double x, double y) {
return Math.sqrt(x*x+y*y) < 100;
}
public static void main(String[] args) throws Exception {
Fish nemo = new Fish();
Fish marlin = new Fish();
while(true) {
nemo.move();
marlin.move();
System.out.println("Nemo: " + nemo);
System.out.println("Marlin: " + marlin);
Thread.sleep(500);
}
}
}
im tring to animate motion of the mouse from 1 button to another in an array with the class robot.
here are the two methods I used:
public void optimusprime(int row, int column, JButton current) throws InterruptedException {
Point p;
Point p2;
double x;
double y;
double x2;
double y2;
double conx = 0;
double m;
double b;
double cony;
p = current.getLocationOnScreen();
x = (int)( p.getX() + 30.5);
y = (int)( p.getY() + 30.5);
optimus((int) x, (int) y);
p2 = mesa[row][column].getLocationOnScreen();
x2 = (int) (p2.getX() + 30.5);
y2 = (int) (p2.getY() + 30.5);
m = (y2 - y) / (x2 - x);
b = y - (m * x);
while (conx != x2) {
conx = x;
cony = (m * conx) + b;
optimus((int) conx, (int) cony);
conx++;
Thread.sleep(500);
}
}
public void optimus(int x, int y) {
try {
Robot robot = new Robot();
robot.mouseMove(x, y);
} catch (AWTException e) {
}
}
can any 1 help me here or at least give a recommendation?. got stock in an endless loop(had to shutdown the pc) and it didnt work at all; Im new to java it could be several stupid mistakes ;
The problem may be that your conx never truly equals your x2 because you're doing all your math as doubles. That would mean that conx would go from being slightly less than x2 to being slightly greater than x2 and would either bounce back and forth between the two or would continue moving along its current trajectory. You will want to add some logic to make sure you don't step over your target, which you could do by setting a threshold for once it's close enough or by stopping as soon as you over step it.