Rectangle rEnemy = new Rectangle();
rEnemy.setBounds(0,0,40,40);
Rectangle rPlayer = new Rectangle();
rPlayer.setBounds(200,0,40,40);
my question: how can i make detection/intersection for rPlayer using something like "line" long for 100px?
example: rEnemy is at (0,0), rPlayer is at (100,0) and now rPlayer is intersecting line. there is a method rPlayer.intersect(rEnemy); but i what keep them 100px away from each other and get detection. of course i mean line which is aplicable for others positions of our rectangles because rPlayer and rEnemy are still in move.
I'm not exactly sure what you want, it sounds like you want to check if they are 100px away but intersecting on the x (or y) coordinate, not a 100px radius.
If you're trying to detect if they are within that bounds, you could merely make 1 or 2 rectangles that extend 100px in the x and y coordinates of either the enemy or player and check if the other piece intersects that.
But it would probably be better to just add 100px to the x coordinate of the enemy and check if the player comes within that boundary, that way you aren't drawing more rectangles. I just mentioned that before because I thought it might be easier to visualize.
I just slove this by creating 3rd rect starting from rEnemy cords and making it width and height to rPlayer cords, then:
double calculate = Math.pow(Math.abs(rPlayer.x-rEnemy.x-Camera.posX), 2)+Math.pow(Math.abs(rEnemy.y-rPlayer.y+Camera.posY), 2);
int distance = (int)Math.sqrt(calculate);
variable distance is value of px which separate rPlayer and rEnemy at any position in shortest way.
Related
I am working on a 2D java game engine using AWT canvas as a basis. Part of this game engine is that it needs to have hitboxes with collision. Not just the built in rectangles (tried that system already) but I need my own Hitbox class because I need more functionality. So I made one, supports circular and 4-sided polygon shaped hitboxes. The way the hitbox class is setup is that it uses four coordinate points to serve as the 4 corner vertices that connect to form a rectangle. Lines are draw connecting the points and these are the lines that are used to detect intersections with other hitboxes. But I now have a problem: rotation.
There are two possibilities for a box hitbox, it can just be four coordinate points, or it can be 4 coordinate points attached to a gameobject. The difference is that the former is just 4 coordinates based on 0,0 as the ordin while the attached to gameobject stores offsets in the coordinates rather than raw location data, so (-100,-100) for example represents the location of the host gameobject but 100 pixels to the left, and 100 pixels up.
Online I found a formula for rotating points about the origin. Since Gameobject based hitboxes were centered around a particular point, I figured that would be the best option to try it on. This code runs each tick to update a player character's hitbox
//creates a rectangle hitbox around this gameobject
int width = getWidth();
int height = getHeight();
Coordinate[] verts = new Coordinate[4]; //corners of hitbox. topLeft, topRight, bottomLeft, bottomRight
verts[0] = new Coordinate(-width / 2, -height / 2);
verts[1] = new Coordinate(width / 2, -height / 2);
verts[2] = new Coordinate(-width / 2, height / 2);
verts[3] = new Coordinate(width / 2, height / 2);
//now go through each coordinate and adjust it for rotation
for(Coordinate c : verts){
if(!name.startsWith("Player"))return; //this is here so only the player character is tested
double theta = Math.toRadians(rotation);
c.x = (int)(c.x*Math.cos(theta)-c.y*Math.sin(theta));
c.y = (int)(c.x*Math.sin(theta)+c.y*Math.cos(theta));
}
getHitbox().vertices = verts;
I appologize for poor video quality but this is what the results of the above are: https://www.youtube.com/watch?v=dF5k-Yb4hvE
All related classes are found here: https://github.com/joey101937/2DTemplate/tree/master/src/Framework
edit: The desired effect is for the box outline to follow the character in a circle while maintaining aspect ratio as seen here: https://www.youtube.com/watch?v=HlvXQrfazhA . The current system uses the code above, the effect of which can be seen above in the previous video link. How should I modify the four 2D coordinates to maintain relative aspect ratio throughout a rotation about a point?
current rotation system is the following:
x = x*Cos(theta) - y *Sin(theta)
y = x*Sin(theta) + y *Cos(theta)
where theta is degree of rotation in raidians
You made classic mistake:
c.x = (int)(c.x*Math.cos(theta)-c.y*Math.sin(theta));
c.y = (int)(c.x*Math.sin(theta)+c.y*Math.cos(theta));
In the second line you use modified value of c.x. Just remember tempx = c.x
before calculations and use it.
tempx = c.x;
c.x = (int)(tempx*Math.cos(theta)-c.y*Math.sin(theta));
c.y = (int)(tempx*Math.sin(theta)+c.y*Math.cos(theta));
Another issue: rounding coordinates after each rotation causes distortions and shrinking after some rotations. It would be wise to store coordinates in floats and round them only for output, or remember starting values and apply rotation by accumulated angle to them.
I'm having problems plotting hitboxes in the center of rotating triangle sprites. When I spawn the triangles, I set the collision rectangle like this:
bullet.collisionRect.width = flashingTriangleSprite.getWidth() - 20;
bullet.collisionRect.height = flashingTriangleSprite.getHeight() - 14;
bullet.scale = 0.287f;
Updating is done as follows:
bullet.position.y += bullet.velocity.y;
// center collision rect over triangle sprite
bullet.collisionRect.x =
bullet.position.x + ((flashingTriangleSprite.getWidth() / 2) - bullet.collisionRect.getWidth() / 2);
bullet.collisionRect.y =
bullet.position.y + ((flashingTriangleSprite.getHeight() / 2) - bullet.collisionRect.getHeight() / 2);
if (bullet.scale < 1)
{
bullet.scale += 0.011f;
}
if (bullet.driftDirection == Globals.Direction.LEFT)
{
bullet.rotation -= 3.804f;
bullet.position.x -= bullet.velocity.x;
}
else // drift right
{
bullet.rotation += 3.804f;
bullet.position.x += bullet.velocity.x;
}
This is the result: http://imgur.com/rIvIT8K
As you can see, the hitboxes are not centered. In fact, the hitboxes seem to change position within the triangle sprites depending on the rotation of the triangle sprite. Any ideas what I'm doing wrong?
When determining your hitbox centre position you are targeting the centre of the triangle sprite (a square), but that is not the perfect centre of the drawn triangle.
Therefore your hitbox is always closer to one of the vertices of the triangle (depending on the rotation). Also, your hitboxes are never rotated with the triangle, instead they always appear to be standing vertically.
To place the hitbox in the middle of the triangle you should aim for 1/3 of the height of the sprite (if the triangle has one side flat at the bottom in the base sprite image) and when you are updating the sprite, attempt to update the hitbox rotation to match the sprite rotation.
You could also try making a more accurate triangle hitbox using the PolygonShape, but that's up to you.
I am trying to create a Shape with the centre of the ship being in the middle.
one.x and one.z is the X and Z positions of the ship. The ship size is about 100 on the X, and 50 on the Z.
Shape my = new Rectangle(
(int) one.x - disToLeft, // upper-left corner X
(int) one.z - disToTop, // upper-left corner Y
disToLeft + disToRight, // width
disToTop + disToBottom // height
);
I'm then rotating the Shape, to of course be facing the correct way. This appears to work:
int rectWidth = (disToLeft + disToRight);
int rectHeight = (disToTop + disToBottom);
AffineTransform tr = new AffineTransform();
// rotating in central axis
tr.rotate(
Math.toRadians(one.rotation),
x + (disToLeft + disToRight) / 2,
z + (disToTop + disToBottom) / 2
);
my = tr.createTransformedShape(my);
I am then doing the exact same thing with another Shape, and testing for intersection. This works.
However, it feels like the Shape is the incorrect dimensions. Or something. My ship is colliding very far out to one side (outside where it graphically exists), but through the other side, I can almost go right through the ship before any collision is detected!
Basically the Shapes are simply intersecting at the wrong location. And I cannot work out why. Either the shape, the location, or the rotation must be wrong.
int disToLeft = 100;
int disToRight = 100;
int disToTop = 150;
int disToBottom = 100;
These are the distance from the centre to the left, right, top, and bottom sides.
I am using Z instead of Y because my game is in a 3D world and the sea level is pretty much the same (hence I don't need to worry about Y axis collision!).
Update:
After doing a lot of testing, I have discovered that the top of the rectangle is in the middle! I have done a lot of messing around, but without being able to graphically see the squares, it's been very hard to test.
This means that the box is on the side of the ship, like this:
Obviously when the ship on the left rotates to what it's like in this picture, a collision is detected.
It seems that your rotation is wrong. From my understanding of math it should be
tr.rotate(Math.toRadians(one.rotation), x + (disToRight - disToLeft) /2, z + (disToBottom - disToTop) /2);
Note the signs and the order of the variables
Edit:
Let's take apart the formula:
Your Rectangle is defined like this:
x-coordinate (x): one.x-disToLeft
y-coordinate (y): one.z-disToTop
width: disToLeft+disToRight
height: disToTop+disToBottom
The centre of the Rectangle (where you are rotating) is therefore:
(x+width/2)
(y+height/2)
if you replace x, width, y and height with the declarations above you get
(one.x-disToLeft + (disToLeft+disToRight)/2)
(one.z-disToTop + (disToTop+disToBottom)/2)
This is already the point you need, but it can be simplyfied:
one.x- disToLeft + (disToLeft+disToRight)/2
is equal to
one.x-(2*disToLeft/2)+(disToLeft/2)+(disToRight/2)
is equal to
one.x-(distoLeft/2) + (disToRight/2)
is equal to
one.x+(disToRight-disToLeft)/2
The other coordinate works exactly the same.
I would like to create a Rectangle that has got one side different than the other.
(All lines depicted are meant to be straight lines)
The normal rectangle is generated like new Rectangle(50 /*LocationX*/, 50 */LocationY*/, 50 /*SizeX*/, 100 /*SizeY*/);, and looks like this:
However, I want a constructor like new Rectangle(50 /*LocationX*/, 50 */LocationY*/, 25 /*25 from the centre point for the red line*/, 30 /*30 from the centre point for the blue line*/, 50 /*50 from centre for green line*/, 100 /*100 from centre for yellow line*/);
In other words, I effectively want to keep the shape the same but move the centre point.
How can I do that?
In java, rectangles are defined by upper-left corner coordinates, width and height.
If I understand your question here what describes your rectangle:
pointX, pointY coordinates of a point in the rectangle. Named the point.
distanceToTop distance from the point to the top of the rectangle (green line).
distanceToBottom distance from the point to the bottom of the rectangle (yellow line).
distanceToLeft distance from the point to the left of the rectangle (red line).
distanceToRight distance from the point to the right of the rectangle (blue line).
That given. The upper-left corner of the rectangle has for coordinates:
(pointX - distanceToLeft, pointY - distanceToTop)
And the whole rectangle has for size (width, height):
(distanceToLeft + distanceToRight, distanceToTop + distanceToBottom)
So your instance will be:
Rectangle r = new Rectangle(
pointX - distanceToLeft, // upper-left corner X
pointY - distanceToTop, // upper-left corner Y
distanceToLeft + distanceToRight, // width
distanceToTop + distanceToBottom // height
);
So i've made my own FPS, graphics and guns and all of that cool stuff; When we fire, the bullet should take a random direction inside the crosshair, as defined by:
float randomX=(float)Math.random()*(0.08f*guns[currentWeapon].currAcc)-(0.04f*guns[currentWeapon].currAcc);
float randomY=(float)Math.random()*(0.08f*guns[currentWeapon].currAcc)-(0.04f*guns[currentWeapon].currAcc);
bulletList.add(new Bullet(new float[]{playerXpos, playerYpos, playerZpos}, new float[]{playerXrot+randomX, playerYrot+randomY}, (float) 0.5));
We calculate the randomness in X and Y (say you had a crosshair size (guns[currentWeapon].currAcc) of 10, then the bullet could go 0.4 to any side and it would remain inside the crosshair.
After that is calculated, we send the player position as the starting position of the bullet, along with the direction it's meant to take (its the player's direction with that extra randomness), and finally it's speed (not important atm, tho).
Now, each frame, the bullets have to move, so for each bullet we call:
position[0] -= (float)Math.sin(direction[1]*piover180) * (float)Math.cos(direction[0]*piover180) * speed;
position[2] -= (float)Math.cos(direction[1]*piover180) * (float)Math.cos(direction[0]*piover180) * speed;
position[1] += (float)Math.sin(direction[0]*piover180) * speed;
So, for X and Z positions, the bullet moves according to the player's rotation on the Y and X axis (say you were looking horizontally into Z, 0 degrees on X and 0 on Y; X would move 0*1*speed and Z would move 1*1*speed).
For Y position, the bullet moves according to the rotation on X axis (varies between -90 and 90), meaning it stays at the same height if the player's looking horizontally or moves completely up if the player is looking vertically.
Now, the problem stands as follows:
If i shoot horizontally, everything works beautifully. Bullets spread around the cross hair, as seen in https://dl.dropbox.com/u/16387578/horiz.jpg
The thing is, if i start looking up, the bullets start concentrating around the center, and make this vertical line the further into the sky i look.
https://dl.dropbox.com/u/16387578/verti.jpg
The 1st image is around 40ยบ in the X axis, the 2nd is a little higher and the last is when i look vertically.
What am i doing wrong here? I designed this solution myself can im pretty sure im messing up somewhere, but i cant figure it out :/
Basicly the vertical offset calculation (float)Math.cos(direction[0]*piover180) was messing up the X and Z movement because they'd both get reduced to 0. The bullets would make a vertical line because they'd rotate on the X axis with the randomness. My solution was to add the randomness after that vertical offset calculation, so they still go left and right and up and down after you fire them.
I also had to add an extra random value otherwise you'd just draw a diagonal line or a cross.
float randomX=(float)Math.random()*(0.08f*guns[currentWeapon].currAcc)-(0.04f*guns[currentWeapon].currAcc);
float randomY=(float)Math.random()*(0.08f*guns[currentWeapon].currAcc)-(0.04f*guns[currentWeapon].currAcc);
float randomZ=(float)Math.random()*(0.08f*guns[currentWeapon].currAcc)-(0.04f*guns[currentWeapon].currAcc);
bulletList.add(new Bullet(new float[]{playerXpos, playerYpos, playerZpos}, new float[]{playerXrot, playerYrot}, new float[]{randomX,randomY, randomZ},(float) 0.5));
And the moving code...
vector[0]= -((float)Math.sin(dir[1]*piover180) * (float)Math.cos(dir[0]*piover180)+(float)Math.sin(random[1]*piover180)) * speed;
vector[1]= ((float)Math.sin(dir[0]*piover180)+(float)Math.sin(random[0]*piover180)) * speed;
vector[2]= -((float)Math.cos(dir[1]*piover180) * (float)Math.cos(dir[0]*piover180)+(float)Math.sin(random[2]*piover180)) * speed;
You didn't need to bust out any complex math, your problem was that when you were rotating the bullet around the y axis for gun spread, if you were looking directly up (that is, through the y axis, the bullet is being rotated around the path which its going, which means no rotation whatsoever (imagine the difference between sticking your arm out forwards towards a wall and spinning in a circle, and sticking you arm out towards the sky and spinning in a circle. Notice that your hand doesn't move at all when pointed towards the sky (the y-axis)) and so you get those "diagonal" bullet spreads.
The trick is to do the bullet spread before rotating by the direction the player is looking in, because that way you know that when you are rotating for spread, that the vector is guaranteed to be perpendicular to the x and y axes.
this.vel = new THREE.Vector3(0,0,-1);
var angle = Math.random() * Math.PI * 2;
var mag = Math.random() * this.gun.accuracy;
this.spread = new THREE.Vector2(Math.cos(angle) * mag,Math.sin(angle) * mag);
this.vel.applyAxisAngle(new THREE.Vector3(0,1,0),this.spread.y / 100); //rotate first when angle gaurenteed to be perpendicular to x and y axes
this.vel.applyAxisAngle(new THREE.Vector3(1,0,0),this.spread.x / 100);
this.vel.applyAxisAngle(new THREE.Vector3(1,0,0),player.looking.x); //then add player looking direction
this.vel.applyAxisAngle(new THREE.Vector3(0,1,0),player.looking.y);
this.offset = this.vel.clone()
I don't use java but I hope you get the main idea of what im doing by this javascript. I am rotating a vector going in the negative z direction (default direction of camera) by the spread.y, and spread.x, and then I am rotating by the pitch and yaw of the angle at which the player is facing.