Related
So to give further context lets say I have an image that is 200px by 200px with a rectangle on it, its red below:
I know the height and width of the image, the coordinates of the rectangle and also the height and width of the red rectangle.
So what I need to know is if I flip this whole image (including the rectangle) is there a way to work out what the new coordinates are of the red rectangle? I'd imagine there must be some kind of formula or algorithm I can apply to get these new coordinates.
This was already answered over here. The below is the function that worked best for my use case which is very similar to yours.
def rotate(point, origin, degrees):
radians = np.deg2rad(degrees)
x,y = point
offset_x, offset_y = origin
adjusted_x = (x - offset_x)
adjusted_y = (y - offset_y)
cos_rad = np.cos(radians)
sin_rad = np.sin(radians)
qx = offset_x + cos_rad * adjusted_x + sin_rad * adjusted_y
qy = offset_y + -sin_rad * adjusted_x + cos_rad * adjusted_y
return int(qx), int(qy)
In addition to this sometimes when you rotate the points you get negative values(depending on degrees of rotation), in cases like these you need to add the height and or width of the image you are rotating to the value. In my case below the images were of fixed size (416x416)
def cord_checker(pt1):
for item in pt1:
if item<0:
pt1[pt1.index(item)]=416+item
else: pass
return pt1
finally to get the coordinates of the rotated point
pt1=tuple(cord_checker(list(rotate((xmi,ymi),origin=(0,0),degrees*=))))
*degrees can be 90,180 etc
If the image is centered around the origin (0,0), you can just flip the signs of the x-coordinates to do a horizontal flip or the y-coordinates to do a vertical flip while preserving the origin as your center.
You can also flip an arbitrary image by flipping the signs:
# Horizontal flip
new_x = -x
new_y = y
# Vertical flip
new_x = x
new_y = -y
but the center coordinates will not be the same. If you want the same center coordinates, you'd have to shift it back.
Is there an algorithm for snapping to an isometric grid?
This is the one I came up with:
def Iso(argument0,argument1):
a = round(pygame.mouse.get_pos()[1]/argument1 - pygame.mouse.get_pos()[0]/argument0);
b = round(pygame.mouse.get_pos()[1]/argument1 + pygame.mouse.get_pos()[0]/argument0);
x = (b - a)/2*argument0;
y = (b + a)/2*argument1;
return (x,y)
and it looks like this:
Anyone got any ideas??
Here is my code:
import pygame
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((640,480))
curs=pygame.image.load('white-0.gif').convert()
curs.set_alpha(100)
g1=pygame.image.load('green-0.gif').convert()
tiles=[]
def Iso(argument0,argument1):
a = round(pygame.mouse.get_pos()[1]/argument1 - pygame.mouse.get_pos()[0]/argument0);
b = round(pygame.mouse.get_pos()[1]/argument1 + pygame.mouse.get_pos()[0]/argument0);
x = (b - a)/2*argument0;
y = (b + a)/2*argument1;
return (x,y)
class Tile(object):
def __init__(self,spr,pos1,pos2):
self.pos=(pos1,pos2)
self.spr=spr
while True:
screen.fill((90,90,0))
mse=pygame.mouse.get_pos()
for e in pygame.event.get():
if e.type==QUIT:
exit()
if e.type==MOUSEBUTTONUP:
if e.button==1:
pos=Iso(16,16)
tiles.append(Tile(g1,pos[0],pos[1]))
pos=Iso(16,16)
screen.blit(curs, (pos[0],pos[1]))
for t in tiles:
screen.blit(t.spr,t.pos)
pygame.display.update()
UPDATE:
Managed to get it to work like this:
Just having a few depth issues..
You are converting pixels to an isometric view. Presumably, you want to snap to (isometric) tiles instead.
Multiply your isometric x,y by (width/2),(height/2) where width and height are your isometric tile dimensions. Since that radically changes the scale, you might want to divide both by a constant; if you don't do that, only moving the mouse in the very top left of your screen will make something show up.
Apart from the isometric part, this is exactly what one would do for a top-down grid.
There is this interesting game, that has numbers in a grid, where each number has progressively smaller font. The player's task is to click on the numbers in succession.
I'm interested in the algorithm that creates the boxes for the numbers, I cannot think of a way it works.
Apparently the grid has N numbers (apart from the 1.88 in the picture), number 1 has the biggest font and succesively the font size decreases. Then the numbers are somehow placed on the grid and boxes grow around them. But it doesn't seem totally random, as there are some horizotal lines that go across the whole grid.
Do you have an idea on how this might work?
It looks to me as though the boxes have been generated by successive division. That is, starting with the full rectangle, a dividing line (horizontal or vertical) was placed, and then the two resulting rectangles were subdivided in turn, until there were enough rectangles for the game.
Here's a sketch of the first algorithm I would try. N is the number of rectangles I want to divide the original rectangle into, and A is a critical aspect ratio used to stop the small rectangles getting too narrow. (Perhaps A = 1.5 would be a good start.)
Create an empty priority queue and add the full rectangle to it.
If the length of the priority queue is greater than or equal to N, stop.
Remove the largest rectangle, R, from the priority queue.
Choose whether to divide it horizontally or vertically: if its aspect ratio (width/height) is greater than A, divide it vertically; if less than 1/A, divide it horizontally, otherwise choose at random.
Decide where to put the dividing line. (Perhaps randomly between 40% and 60% along the chosen dimension.)
This divides R into two smaller rectangles. Add both of them to the priority queue. Go to step 2.
When this algorithm completes, there are N rectangles in the queue. Put the number 1 in the largest of them, the number 2 in the second largest, and so on.
It turns out that putting the numbers into the boxes is not quite as straightforward as I assumed in my first attempt. The area metric works well for subdividing the rectangles nicely, but it doesn't work for putting the numbers into the boxes, because for fitting text into a box, the height and width both have to be taken into account (the area is not so useful).
Instead of explaining the algorithm for putting numbers into the boxes, I will just give you some sample code in Python and let you reverse-engineer it!
import heapq, itertools, random
import Image, ImageDraw, ImageFont
# ALGORITHM PARAMETERS
aspect_max = 1.5 # Above this ratio, always divide vertically
aspect_min = 1.0 # Below this ratio, always divide horizontally
div_min = 0.4 # Minimum position for dividing line
div_max = 0.6 # Maximum position for dividing line
digit_ratio = 0.7 # Aspect ratio of widest digit in font
label_margin = 2 # Margin around label (pixels)
class Rectangle(object):
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
self.area = self.w * self.h
self.aspect = float(self.w) / self.h
def __le__(self, other):
# The sense of this comparison is inverted so we can put
# Rectangles into a min-heap and be able to pop the largest.
return other.area <= self.area
def __repr__(self):
return 'Rectangle({0.x}, {0.y}, {0.w}, {0.h})'.format(self)
def divide(self, n):
"""
Divide this rectangle into `n` smaller rectangles and yield
them in order by area (largest first).
"""
def division(l):
return random.randrange(int(l * div_min), int(l * div_max))
queue = [self]
while len(queue) < n:
r = heapq.heappop(queue)
if (r.aspect > aspect_max
or r.aspect > aspect_min
and random.random() < 0.5):
# Vertical division
w = division(r.w)
heapq.heappush(queue, Rectangle(r.x, r.y, w, r.h))
heapq.heappush(queue, Rectangle(r.x + w, r.y, r.w - w, r.h))
else:
# Horizontal division
h = division(r.h)
heapq.heappush(queue, Rectangle(r.x, r.y, r.w, h))
heapq.heappush(queue, Rectangle(r.x, r.y + h, r.w, r.h - h))
while queue:
yield heapq.heappop(queue)
def font_height(self, n):
"""
Return the largest font height such that we can draw `n`
digits in this rectangle.
"""
return min(int((self.w - label_margin * 2) / (digit_ratio * n)),
self.h - label_margin * 2)
def draw_rectangles(rectangles, fontfile):
"""
Create and return an Image containing `rectangles`. Label each
rectangle with a number using the TrueType font in `fontfile`.
"""
rectangles = list(rectangles)
im = Image.new('RGBA', (1 + max(r.x + r.w for r in rectangles),
1 + max(r.y + r.h for r in rectangles)))
draw = ImageDraw.Draw(im)
for digits in itertools.count(1):
rectangles = sorted(rectangles,
key = lambda r: r.font_height(digits),
reverse = True)
i_min = 10 ** (digits - 1)
i_max = 10 ** digits
i_range = i_max - i_min
for i in xrange(i_range):
if i >= len(rectangles): return im
r = rectangles[i]
draw.line((r.x, r.y, r.x + r.w, r.y, r.x + r.w, r.y + r.h,
r.x, r.y + r.h, r.x, r.y),
fill = 'black', width = 1)
label = str(i + i_min)
font = ImageFont.truetype(fontfile, r.font_height(digits))
lw, lh = font.getsize(label)
draw.text((r.x + (r.w - lw) // 2, r.y + (r.h - lh) // 2),
label, fill = 'black', font = font)
rectangles = rectangles[i_range:]
Here's a sample run:
>>> R = Rectangle(0, 0, 400, 400)
>>> draw_rectangles(R.divide(30), '/Library/Fonts/Verdana.ttf').save('q10009528.png')
The pattern of the cuts looks recursive. That is, the process of dividing the region into rectangles consists of cutting a rectangle in two, over and over. There are two cuts that divide the whole rectangular region (the horizontal cuts above and below 1), so we can't tell which cut came first, but we see the cuts as a kind of tree: the cut that separates 1 from 10 produced a large rectangle below it (20, 21, 4, 10, etc.), which was then divided by the vertical cut between 21 and 4, the rectangle containing 4 was later divided by the cut that separates 4 and 14, and so on. There are N cuts that produce N regions plus one leftover ("1.88") which is not necessary but which might give us a clue.
Now we just have to figure out the order of the cuts, the choice of proportion and the choice of orientation.
Consecutive numbers are rarely neighbors, so it looks as if numbers are not assigned as the cutting progresses. Instead, the region is chopped into rectangles, the rectangles are sorted by size and then numbers are assigned (notice that 20 and 21 are neighbors, but they were formed by other cuts after the one that divides them).
A plausible hypothesis for the order of the cuts is that the algorithm always cuts the largest rectangle. If that were not true, we might see, e.g., 14 bigger than 15 and 18 combined, and I see no example of that.
Proportion... With careful measurement we could see the actual distribution of proportions, but I don't feel like doing that much work. We see no very long, thin rectangles and no 50/50 cuts, so at a guess I'd say the algorithm chooses randomly, in some range like [0.6, 0.8]. Maybe it tries to avoid making a rectangle very close to the size of a rectangle that already exists. After all the cuts, the rectangle chosen to be left over ("1.88") is neither the biggest nor the smallest; maybe it's random, maybe it's the second-biggest, maybe it's something else-- more examples would be useful.
The orientation seems to be strongly biased towards cutting rectangles across their narrow width, rather than "lengthwise". This has the effect of producing rectangles more like squares and less like books on a shelf. The only possible exception I can see is the 1-9 cut, which might divide the block whose lower-right number is 1 lengthwise. But that depends on the order of cuts above and below 1, so it leads to a hypothesis: the algorithm always cuts a rectangle along its shorter dimension, and the 1-9 cut was actually the first.
That's about as far as I can go, short of breaking out a ruler and calculator.
I've always wondered the easiest way to figure out whether or not a point lies within a triangle, or in this instance, a rectangle cut into half diagonally.
Let's say I have a rectangle that is 64x64 pixels. With this rectangle, I want to return a TRUE value if a passed point is within the upper-left corner of the rectangle, and FALSE if it isn't.
-----
| /|
| / |
|<__|
Horray for bad ASCII art.
Anyway, the hypothetical points for this triangle that would return TRUE would be (0,0) and (63,0) and (0, 63). If a point lands on a line (e.g., 50,0) it would return TRUE as well.
Assuming 0,0 is in the upper-left corner and increases downwards...
I've had a possible solution in my head, but it seems more complicated than it should be - taking the passed Y value, determining where it would be in the rectangle, and figuring out manually where the line would cut at that Y value. E.g, a passed Y value of 16 would be quarter height of the rectangle. And thus, depending on what side you were checking (left or right), the line would either be at 16px or 48px, depending on the direction of the line. In the example above, since we're testing the upper-left corner, at 16px height, the line would be at 48px width
There has to be a better way.
EDIT:
The rectangle could also look like this as well
-----
|\ |
| \ |
|__>|
But I'm figuring in most cases the current answers already provided should still hold up...
Top-left/bottom-right triangles: For all points in the top-left triangle, x+y<=64. Points in the bottom-right triangle have x+y>64.
(for a rectangle of size (w,h) use w*y+h*x-w*h<0)
Top-right/bottom-left triangles: For all points in the bottom-left triangle, x<=y. Points in the top-right triangle have x>y.
(for a rectangle of size (w,h) use h*x-w*y<0)
How did we get there?
For a rectangle of dimensions (w,h) and TL/BR triangles, the equation of the diagonal is (try it out! assign x=0 and check that you get y==h, and assign y=0 and check that x==w)
h*x + w*y - w*h = 0
Points on one side of that line will have
h*x + w*y - w*h > 0
While points on the other will have
h*x + w*y - w*h < 0
Inserting 64 for both w and h, we get:
64x + 64y - 64*64 < 0
Dividing by 64 gets us:
x+y < 64
For TR/BL triangles, the line equation and the resulting inequalities are:
h*x - w*y = 0
h*x - w*y < 0
h*x - w*y > 0
Inserting 64 for w and h, we get
64x-64y < 0
=> x<y
you can represent the triangle with three affine functions
take the unit triangle with corners at (0, 0), (1, 0) and (1, 1). the sides are represented by the three lines
y = 0
x = 1
y = x
So the interior and boundry of the triangle are given as the intersection of the sets
x >= 1
y >= 0
y <= x
so given a point, (x, y), you just need to verify that it satisfies those three inequalities.
You can of course generalize this to any triangle using the fact that any affine function (representing a line) can be written in the form y = mx + b.
The equation for the line looks like this :
y = mx + b
So, if you insert your x and y-Values into that equation, it will probably not hold anymore. Let's reformulate it:
mx + b - y = 0
Same thing, different look. Again, the result is probably not zero. But, the result will now tell you whether it's on the one side of the line or the other.
Now you just have to find out whether the point is inside your rectangle.
Lets assume your right angled triangle has one corner at 0,0 and the diagonal corner at a,b.
So y=mx+c c=0 as we start at the origin.
m=b/a
So y=bx/a
To know which half of the triangle your point (c,d) falls in
if (d<=(bc/a)) {//point is in bottom half}
if (d>(bc/a)) {//point is in top half}
I think...
A simple option is to use a ray casting algorithm. Whilst perhaps a little overkill for what you need, it does have the advantage that it will work with more complex triangles and polygons.
Loosely, the algorithm takes an imaginary point in a direction (infinitely off to the left, for example) and casts a ray to your test point; you then calculate whether each line of your triangle crosses that infinitely long line. If you get an odd number of crossings, your point is inside your triangle; even and you're out of your triangle
I'm writing a script where icons rotate around a given pivot (or origin). I've been able to make this work for rotating the icons around an ellipse but I also want to have them move around the perimeter of a rectangle of a certain width, height and origin.
I'm doing it this way because my current code stores all the coords in an array with each angle integer as the key, and reusing this code would be much easier to work with.
If someone could give me an example of a 100x150 rectangle, that would be great.
EDIT: to clarify, by rotating around I mean moving around the perimeter (or orbiting) of a shape.
You know the size of the rectangle and you need to split up the whole angle interval into four different, so you know if a ray from the center of the rectangle intersects right, top, left or bottom of the rectangle.
If the angle is: -atan(d/w) < alfa < atan(d/w) the ray intersects the right side of the rectangle. Then since you know that the x-displacement from the center of the rectangle to the right side is d/2, the displacement dy divided by d/2 is tan(alfa), so
dy = d/2 * tan(alfa)
You would handle this similarily with the other three angle intervals.
Ok, here goes. You have a rect with width w and depth d. In the middle you have the center point, cp. I assume you want to calculate P, for different values of the angle alfa.
I divided the rectangle in four different areas, or angle intervals (1 to 4). The interval I mentioned above is the first one to the right. I hope this makes sense to you.
First you need to calculate the angle intervals, these are determined completely by w and d. Depending on what value alfa has, calculate P accordingly, i.e. if the "ray" from CP to P intersects the upper, lower, right or left sides of the rectangle.
Cheers
This was made for and verified to work on the Pebble smartwatch, but modified to be pseudocode:
struct GPoint {
int x;
int y;
}
// Return point on rectangle edge. Rectangle is centered on (0,0) and has a width of w and height of h
GPoint getPointOnRect(int angle, int w, int h) {
var sine = sin(angle), cosine = cos(angle); // Calculate once and store, to make quicker and cleaner
var dy = sin>0 ? h/2 : h/-2; // Distance to top or bottom edge (from center)
var dx = cos>0 ? w/2 : w/-2; // Distance to left or right edge (from center)
if(abs(dx*sine) < abs(dy*cosine)) { // if (distance to vertical line) < (distance to horizontal line)
dy = (dx * sine) / cosine; // calculate distance to vertical line
} else { // else: (distance to top or bottom edge) < (distance to left or right edge)
dx = (dy * cosine) / sine; // move to top or bottom line
}
return GPoint(dx, dy); // Return point on rectangle edge
}
Use:
rectangle_width = 100;
rectangle_height = 150;
rectangle_center_x = 300;
rectangle_center_y = 300;
draw_rect(rectangle_center_x - (rectangle_width/2), rectangle_center_y - (rectangle_center_h/2), rectangle_width, rectangle_height);
GPoint point = getPointOnRect(angle, rectangle_width, rectangle_height);
point.x += rectangle_center_x;
point.y += rectangle_center_y;
draw_line(rectangle_center_x, rectangle_center_y, point.x, point.y);
One simple way to do this using an angle as a parameter is to simply clip the X and Y values using the bounds of the rectangle. In other words, calculate position as though the icon will rotate around a circular or elliptical path, then apply this:
(Assuming axis-aligned rectangle centered at (0,0), with X-axis length of XAxis and Y-axis length of YAxis):
if (X > XAxis/2)
X = XAxis/2;
if (X < 0 - XAxis/2)
X = 0 - XAxis/2;
if (Y > YAxis/2)
Y = YAxis/2;
if (Y < 0 - YAxis/2)
Y = 0 - YAxis/2;
The problem with this approach is that the angle will not be entirely accurate and the speed along the perimeter of the rectangle will not be constant. Modelling an ellipse that osculates the rectangle at its corners can minimize the effect, but if you are looking for a smooth, constant-speed "orbit," this method will not be adequate.
If think you mean rotate like the earth rotates around the sun (not the self-rotation... so your question is about how to slide along the edges of a rectangle?)
If so, you can give this a try:
# pseudo coode
for i = 0 to 499
if i < 100: x++
else if i < 250: y--
else if i < 350: x--
else y++
drawTheIcon(x, y)
Update: (please see comment below)
to use an angle, one line will be
y / x = tan(th) # th is the angle
the other lines are simple since they are just horizontal or vertical. so for example, it is x = 50 and you can put that into the line above to get the y. do that for the intersection of the horizontal line and vertical line (for example, angle is 60 degree and it shoot "NorthEast"... now you have two points. Then the point that is closest to the origin is the one that hits the rectangle first).
Use a 2D transformation matrix. Many languages (e.g. Java) support this natively (look up AffineTransformation); otherwise, write out a routine to do rotation yourself, once, debug it well, and use it forever. I must have five of them written in different languages.
Once you can do the rotation simply, find the location on the rectangle by doing line-line intersection. Find the center of the orbited icon by intersecting two lines:
A ray from your center of rotation at the angle you desire
One of the four sides, bounded by what angle you want (the four quadrants).
Draw yourself a sketch on a piece of paper with a rectangle and a centre of rotation. First translate the rectangle to centre at the origin of your coordinate system (remember the translation parameters, you'll need to reverse the translation later). Rotate the rectangle so that its sides are parallel to the coordinate axes (same reason).
Now you have a triangle with known angle at the origin, the opposite side is of known length (half of the length of one side of the rectangle), and you can now:
-- solve the triangle
-- undo the rotation
-- undo the translation