Drawing a rectangle inside a rectangle - java

I feel a little silly asking this but i'm not able to figure it out.. I am trying to draw a rectangle inside another rectangle and the math i'm using must be off. the inside rectangle is always one pixel to short.
b.fillRect( rectangleX+rectangleOutlineSize, rectangleY+rectangleOutlineSize, rectangleWidth-rectangleOutlineSize*2, rectangleHeight);
Its probably simple but I have been stuck on it for a hour and I have had trouble with it in the past.

In programming the coordinate system is a bit
weird, not exactly as (the usual one) in math.
*---------------------------------------> X +
|
|
|
|
|
|
|
v
Y +
I guess you're having a problem with that.
The * is the (0,0) which is usually the upper left
corner of your drawing area (e.g. of your screen).
Try something along these lines.
b.fillRect( x, y, width, height );
b.fillRect( x + (width-w)/2.0, y + (height-h)/2.0, w, h );
width - the width of the big rectangle
height - the height of the big rectangle
x,y - upper left corner of the big rectangle
w,h - width, height of the small rectangle

Related

Slick tiledmap render explanation

Im trying to render a map for a game I am making using tiled map from the slick class but im having a lot of trouble understanding the difference between the parameters x and y. Below is a googled explanation but im not understanding it
public void render(int x,
int y,
int sx,
int sy,
int width,
int height)
Render a section of the tile map
Parameters:
x - The x location to render at
y - The y location to render at
sx - The x tile location to start rendering
sy - The y tile location to start rendering
width - The width of the section to render (in tiles)
height - The height of the secton to render (in tiles)
My game consists of a car and a camera locked onto it which will follow the car around on the map. The map starts to render as the car move. Could someone give me an explanation on how x and y and sx and sy applies to this.
The render function takes a rectangular area of tiles and draws them onto a rectangular area of pixels on the screen.
x and y specify the top left corner of the pixel rectangle
sx and sy specify the top left corner of the tile rectangle
width and height specify the area of the tile rectangle

java, determine if circle is inside an area

Hi im new to programming and im trying to code an algorithm in java to determine if a circle is in a rectangular area
I have the radius of the circle and the point in the middle of it(the center)
|_____________________________________________________
|
|
|
| circle
|
|
|
|
|(0,0)________________________________________________
the bottom left corner represent the coordinate (0,0)
this is what I have so far but I know I have an error somewhere which I can't find
if (mCenter.getmX() + mRadius > width ||
mCenter.getmY() + mRadius > height ||
mCenter.getmX() - mRadius < 0 ||
mCenter.getmY() - mRadius < 0) {
return false; //not inside area
}
else { return true; }
In this code mCenter is a Point with a x and y coordinate, mRadius is the circle radius and width and height are the width/height of the area
thanks
You didn't say what the symptom is, but your helpful diagram above uses the ordinary mathematical coordinate system while your posted code uses awt.image.BufferedImage. Swing and most 2D computer graphics systems use a different coordinate system that's more convenient for laying out content in reading order.
Per GraphicsConfiguration#getDefaultTransform():
Coordinates in the coordinate space defined by the default
AffineTransform for screen and printer devices have the origin in the
upper left-hand corner of the target region of the device, with X
coordinates increasing to the right and Y coordinates increasing
downwards.
I think it's possible to set up a GraphicsConfiguration with a different transform. (I don't know how to do it.) Not so for awt.image.BufferedImage:
All BufferedImage objects have an upper left corner coordinate of (0, 0).
javax.swing.SwingUtilities has coordinate conversion methods.
P.S. Calling image.setRGB() for each pixel will be slow compared to passing the entire image into setRGB(int startX, int startY, int w, int h, int[] rgbArray, int offset, int scansize) or setData(Raster r). Usually a frame buffer is held in a 1-D array that's treated like a 2-D array, with scansize indicating the width of a scan line within this buffer.

Dynamic Programming and Knapsack Application

Im studying dynamic programming and am looking to solve the following problem, which can be found here http://www.cs.berkeley.edu/~vazirani/algorithms/chap6.pdf:
You are given a rectangular piece of cloth with dimensions X by Y, where X and Y are positive integers, and a list of n products that can be made using the cloth. For each product i in [1,n] you know that a rectangle of cloth of dimensions ai by bi is needed and that the final selling price of the product is ci. Assume that ai, bi, and ci are all positive integers. You have a machine that can cut any rectangular piece of cloth into two pieces either horizontally or vertically. Design an algorithm that finds the best strategy for cutting an X by Y piece of cloth so that the products made from the resulting pieces give the maximum sum of selling prices. You are free to make as many copies of a given product as you wish, or none if desired. (From Algorithms by Dasgupta, Papadimitriou, and Vazirani.)
It seems we have a sort of 2-dimensional knapsack problem, but I'm thinking it may be possible to just solve it with the traditional knapsack algorithm by considering the weights as the areas of the rectangles. Does this seem like a reasonable approach?
This is a programming assignment for a course I'm taking so please only include conceptual discussion and/or pseudo-code to illustrate ideas.
So you start with a X * Y rectangle. Say the optimal solution involves making a vertical (or horizontal) cut, then you have two new rectangles with dimensions X * Y1 and X * Y2 with Y1 + Y2 = Y. Since you want to maximize your profit, you need to maximize the profit on these new rectangles (optimal substructure). So your initial recursion goes as follows: f(X, Y) = max(f(X, Y1) + f(X, Y2), f(X1, Y) + f(X2, Y)) for all posible values of X1, X2 (horizontal cut) and Y1, Y2 (vertical cut).
Now the question is when do I actually decide to make a product ? You can decide to make a product when one of its dimensions equals one of the dimensions of your current rectangle (why ? Because if this doesn't hold, and the optimal solution includes making this product, then sooner or later you will need to make a vertical (or horizontal) cut and this case is already handled in the initial recursion), so you make the appropriate cut and you have a new rectangle X * Y1 (or X1 * Y), depending on the cut you made to obtain the product), in this case the recursion becomes f(X, Y) = cost of product + f(X1, Y).
The solution of the original problem is f(X, Y). The running time of this dp solution would be O(X * Y * (X + Y + number of available products)): you have X * Y possible rectangles, for each of these you try every possible cut (X + Y) and you try to make one of the available products out of this rectangle.
Also, check out this similar problem: Sharing Chocolate from the 2010 ICPC World Finals.
I think you should focus on the fact that the machine cuts the cloth into two pieces. What can fit in each of those two pieces? Consider the following:
+-------------+-------------------+
| | Piece B |
| | |
| Piece A +----------+--------+
| | | |
| | | |
| | | Piece |
+-------------+----------+ C |
| | |
| Piece D | |
+------------------------+--------+
These four fit in the cloth, but not in a way that's possible to achieve with three cuts. (Possibly a different arrangement would allow that with these particular pieces; think of this as a conceptual diagram, not to scale. My ascii art skills are limited today.)
Focussing on "where is the cut" should give you the dynamic programming solution. Good luck.
Please include the necessary conditions for rectangle of size (0, something) or (something, 0) in the Rect() function.
optimize() {
Rectangle memo[width][height]
optimize(0,0,totalwidth, totalheight, memo)
}
optimize(x, y, width, height, memo) {
if memo[width][height] != null
return memo[width][height]
rect = new Rectangle(width, height, value = 0)
for each pattern {
//find vertical cut solution
leftVerticalRect = optimize (x, y + pattern.height, pattern.width, height-pattern.height,memo)
rightVerticalRect = optimize(x + pattern.width, y, width-pattern.width, height)
verticalcut = new Cut(x + pattern.width, y, x + pattern.width, y + height)
//find horizontal cut solution
topHorizontalRect = optimize ( --parameters-- )
bottomHortizonalRect = optimize( --parameters--)
horizontalcut = new Cut( --parameters--)
//see which solution is more optimal
if (leftVerticalRect.val + rightVerticalRect.val > topHorizontalRect.val + bottomHorizontalRect.val)
subprobsolution = vertical cut solution
else
subprobsolution = horizontal cut solution
//see if the solution found is greater than previous solutions to this subproblem
if (subprobsolution.value + pattern.value > rect.value) {
rect.subrect1 = subprobsolutionrect1
rect.subrect2 = subprobsolutionrect2
rect.pattern = pattern
rect.cut = subprobsolutioncut
rect.value = rect.subrect1.value + rect.subrect2.value + rect.pattern.value
}
}
memo[width][height] = rect
return rect
}

draw ellipse using center point (not upper left corner)

I try to find a solution for drawing ellipses based on the center point, not the upper left corner as it is specified in the constructor of Ellipse2D.Double. As seen in the picture the ellipses should have the same center point and scale, is that somehow possible?
Thanks in advance for your help.
If (x,y) is the center you want to use and you can only specify the upper left corner, then use the following:
private Ellipse2D getEllipseFromCenter(double x, double y, double width, double height)
{
double newX = x - width / 2.0;
double newY = y - height / 2.0;
Ellipse2D ellipse = new Ellipse2D.Double(newX, newY, width, height);
return ellipse;
}
If called with the center point and the width and height, this will "transform" your center point to the upper left corner and create an Ellipse2D which is located just as you want it to be.
The 'Upper' coordinate is misleading , it only works assuming y >=0 ( which works fine for a screen referential , bur not if you use the primitive with y <0 , for instance calculating object collisions )
With the usual math referential , where y<0 is possible , up is at the bottom
so it lacks a general definition not to get confused
The exact definition is that x and y are the min coordinates of the bounding rectangle.
It can be 'up' or 'down' ( relatively to your screen i suppose ) depending on the y axis orientation and y coordinate sign

How to position a Node along a circular orbit around a fixed center based on mouse coordinates (JavaFX)?

Im trying to get into some basic JavaFX game development and I'm getting confused with some circle maths.
I have a circle at (x:250, y:250) with a radius of 50.
My objective is to make a smaller circle to be placed on the circumference of the above circle based on the position of the mouse.
Where Im getting confused is with the coordinate space and the Trig behind it all.
My issues come from the fact that the X/Y space on the screen is not centered at 0,0. But the top left of the screen is 0,0 and the bottom right is 500,500.
My calculations are:
var xpos:Number = mouseEvent.getX();
var ypos:Number = mouseEvent.getY();
var center_pos_x:Number = 250;
var center_pos_y:Number = 250;
var length = ypos - center_pos_y;
var height = xpos - center_pos_x;
var angle_deg = Math.toDegrees(Math.atan(height / length));
var angle_rad = Math.toRadians(angle_deg);
var radius = 50;
moving_circ_xpos = (radius * Math.cos(angle_rad)) + center_pos_x;
moving_circ_ypos = (radius * Math.sin(angle_rad)) + center_pos_y;
I made the app print out the angle (angle_deg) that I have calculated when I move the mouse and my output is below:
When the mouse is (in degrees moving anti-clockwise):
directly above the circle and horizontally inline with the center, the angle is -0
to the left and vertically centered, the angle is -90
directly below the circle and horizontally inline with the center, the angle is 0
to the right and vertically centered, the angle is 90
So, what can I do to make it 0, 90, 180, 270??
I know it must be something small, but I just cant think of what it is...
Thanks for any help
(and no, this is not an assignment)
atan(height/length) is not enough to get the angle. You need to compensate for each quadrant, as well as the possibility of "division-by-zero". Most programming language libraries supply a method called atan2 which take two arguments; y and x. This method does this calculation for you.
More information on Wikipedia: atan2
You can get away without calculating the angle. Instead, use the center of your circle (250,250) and the position of the mouse (xpos,ypos) to define a line. The line intersects your circle when its length is equal to the radius of your circle:
// Calculate distance from center to mouse.
xlen = xpos - x_center_pos;
ylen = ypos - y_center_pos;
line_len = sqrt(xlen*xlen + ylen*ylen); // Pythagoras: x^2 + y^2 = distance^2
// Find the intersection with the circle.
moving_circ_xpos = x_center_pos + (xlen * radius / line_len);
moving_circ_ypos = y_center_pos + (ylen * radius / line_len);
Just verify that the mouse isn't at the center of your circle, or the line_len will be zero and the mouse will be sucked into a black hole.
There's a great book called "Graphics Gems" that can help with this kind of problem. It is a cookbook of algorithms and source code (in C I think), and allows you to quickly solve a problem using tested functionality. I would totally recommend getting your hands on it - it saved me big time when I quickly needed to add code to do fairly complex operations with normals to surfaces, and collision detections.

Categories