I have two functions which recieve co-ordinates that are not returning the correct output.
One receives the position of the mouse relative to the element and returns a grid co ordinate for isometric tiles.
The other function essentially reverses this process from iso tile back to pixel position on the screen.
When i send in a co-ordinate for my mouse position and convert it to isometric, then convert it back to pixel position i get a different result from what i started with by a large margin rather than the rounding of the tile size - suggesting I got the maths wrong some where, but am not sure where.
My two functions are:
function isoToScreen(isoX,isoY){ //recieves simple grid co-ordinate (int,int)
var x = (isoX - isoY) * (grid.getWidth()/2),
y = (isoX + isoY) * (grid.getHeight()/2);
//need to remove the camera offset to get the relative position
x = camera.removeOffsetX(x);
y = camera.removeOffsetY(y);
return {'x':x,'y':y};
}
function screenToIso(x,y){ //receives mouse position relative to canvas
//add camera offset to get the correct isometric grid
x = camera.addOffsetX(x);
y = camera.addOffsetY(y);
var isoX = x / (grid.getWidth()/2) + y / (grid.getHeight()/2),
isoY = y / (grid.getHeight()/2) - x / (grid.getWidth()/2);
return {'x':Math.floor(isoX),'y':Math.floor(isoY)}
}
Just some extra info, grid height == 46 and grid width == 92.
Can any one see where i am going wrong in the my maths logic?
In screenToIso you are multiplying the vector [x;y] by the matrix:
[ 2 / grid.getWidth(), 2 / grid.getHeight()]
[ -2 / grid.getWidth(), 2 / grid.getHeight()]
Its inverse is:
[grid.getWidth() / 4, -grid.getWidth() / 4]
[grid.getHeight() / 4, grid.getHeight() / 4]
Hence the first two lines of isoToScreen should be:
var x = (grid.getWidth() / 4) * isoX - (grid.getWidth() / 4) * isoY;
var y = (grid.getHeight() / 4) * isox + (grid.getHeight() / 4) * isoY;
Related
Hello i'm currently trying to draw a line through two long/lat lines to create a triangle. So far i have manged to draw a line through but the line is not perpendicular and looks skewed. Here is my code:
startPosition = [-0.17640, 51.426700];
endPosition = [0.17640, 51.796700];
triangleSizeY = (endPosition [1] - startPosition[1]) / 6;
/*subtract
end from start to work out direction and also use this divided by 6 to
get distance*/
triangleSize *= -1;
triangleSizeX = (endPosition [0] - startPosition[0]) / 6;
/*subtract
end from start to work out direction and also use this divided by 6 to
get distance*/
triangleSize *= -1;
var cx = (startPosition[0] + endPosition[0]) / 2;
var cy = (startPosition[1] + endPosition[1]) / 2;
var dx = (endPosition[0] - startPosition[0]) / 2;
var dy = (endPosition[1] - startPosition[1]) / 2;
positions[0] = [midPoint[0] + triangleSizeX, midPoint[1] +
triangleSizeY];
positions[1] = [cx - dy, cy + dx];
positions[2] = [cx + dy, cy - dx];
This is what it looks like:
First, lat/lon are angular so you can not do linear type distances. The steps you need to take to solve this:
Compute the distance between the 2 lat/lon pairs you want a perpendicular line from.
Take half the distance computed from the above step to get you the midpoint range.
Calculate the bearing between the 2 lat/lon pairs. (see reference below on computing a bearing from 2 lat/lon's)
With the half distance and bearing, you can compute the lat/lon of the midpoint. This is called computing a lat/lon based on a range and bearing. (See the reference below.)
Now you can go perpendicular from the midpoint by adding/subtracting 90 degrees from the bearing in step 3. Decide on a range you want to compute the new lat/lon from a range/bearing like in step 4.
This site (https://www.movable-type.co.uk/scripts/latlong.html) has the calculations you need to do this. Also, since the distance is relatively small, you can use the Equirectangular approximation over Haversine for distance calculation.
I'm trying to draw the perimeter of a circle depending on the angle inputed by the user. The angle determines the perimeter completion : 360° being the full circle, 180 half of the circle, and so on.
My problem is : given the radius, the angle and the center coordinates of the circle, how can I dynamically compute the path of the perimeter ?
I know it's probably basic math but everything I tried so far didn't work.
Here is my fiddle : https://jsfiddle.net/Hal_9100/L311qq88/
My problem is finding the right formula for the x and y coordinates of the path :
var x = i * (radius * Math.cos(angle)) + centerX;
var y = i * (radius * Math.sin(angle)) + centerY;
Am I going all wrong here ?
Here is an example of what I'm trying to do : please note that only the black perimeter should be drawn : I just used the dotted red lines to give a visual example of how the perimeter should be drawn depending on the value given by the user.
Yes, the problem is your maths. Here is the correct way to calculate the x,y coordinate pairs (note that the iteration is from zero to the required angle, not from zero to the radius):
for (var i = 0; i <= angle; i++) {
var x = (radius * Math.cos((i-90)*Math.PI/180)) + centerX;
var y = (radius * Math.sin((i-90)*Math.PI/180)) + centerY;
Your fiddle works fine if you substitute these three lines.
I am currently developing a game, which requires a map consisting of various tile images. I managed to make them display correctly (see second image) but I am now unsure of how to calculate the clicked tile from the mouse position.
Are there any existing libraries for this purpose?
Please also note, that the tile images aren't drawn perfectly "corner-facing-camera", they are slightly rotated clockwise.
Isometric Transformations
Define a projection
Isometric display is the same as standard display, the only thing that has changed is the direction of the x and y axis. Normally the x axis is defined as (1,0) one unit across and zero down and the y axis is (0,1) zero units across and one down. For isometric (strictly speaking your image is a dimetric projection) you will have something like x axis (0.5,1) and y axis (-1,0.5)
The Matrix
From this you can create a rendering matrix with 6 values Two each for both axes and two for the origin, which I will ignore for now (the origin) and just use the 4 for the axis and assume that the origin is always at 0,0
var dimetricMatrix = [0.5,1.0,-1,0.5]; // x and y axis
Matrix transformation
From that you can get a point on the display that matches a given isometric coordinate. Lets say the blocks are 200 by 200 pixels and that you address each block by the block x and y. Thus the block in the bottom of your image is at x = 2 and y = 1 (the first top block is x = 0, y = 0)
Using the matrix we can get the pixel location of the block
var blockW = 200;
var blockH = 200;
var locX = 2;
var locY = 1;
function getLoc(x,y){
var xx,yy; // intermediate results
var m = dimetricMatrix; // short cut to make code readable
x *= blockW; // scale up
y *= blockH;
// now move along the projection x axis
xx = x * m[0];
yy = x * m[1];
// then add the distance along the y axis
xx += y * m[2];
yy += y * m[3];
return {x : xx, y : yy};
}
Befoer I move on you can see that I have scaled the x and y by the block size. We can simplify the above code and include the scale 200,200 in the matrix
var xAxis = [0.5, 1.0];
var yAxis = [-1, 0.5];
var blockW = 200;
var blockH = 200;
// now create the matrix and scale the x and y axis
var dimetricMatrix = [
xAxis[0] * blockW,
xAxis[1] * blockW,
yAxis[0] * blockH,
yAxis[1] * blockH,
]; // x and y axis
The matrix holds the scale in the x and y axis so that the two numbers for x axis tell us the direction and length of a transformed unit.
Simplify function
And redo the getLoc function for speed and efficiency
function transformPoint(point,matrix,result){
if(result === undefined){
result = {};
}
// now move along the projection x axis
result.x = point.x * matrix[0] + point.y * matrix[2];
result.y = point.x * matrix[1] + point.y * matrix[3];
return result;
}
So pass a point and get a transformed point back. The result argument allows you to pass an existing point and that saves having to allocate a new point if you are doing it often.
var point = {x : 2, y : 1};
var screen = transformPoint(point,dimetricMatrix);
// result is the screen location of the block
// next time
screen = transformPoint(point,dimetricMatrix,screen); // pass the screen obj
// to avoid those too
// GC hits that kill
// game frame rates
Inverting the Matrix
All that is handy but you need the reverse of what we just did. Luckily the way matrices work allows us to reverse the process by inverting the matrix.
function invertMatrix(matrix){
var m = matrix; // shortcut to make code readable
var rm = [0,0,0,0]; // resulting matrix
// get the cross product of the x and y axis. It is the area of the rectangle made by the
// two axis
var cross = m[0] * m[3] - m[1] * m[2]; // I call it the cross but most will call
// it the determinate (I think that cross
// product is more suited to geometry while
// determinate is for maths geeks)
rm[0] = m[3] / cross; // invert both axis and unscale (if cross is 1 then nothing)
rm[1] = -m[1] / cross;
rm[2] = -m[2] / cross;
rm[3] = m[0] / cross;
return rm;
}
Now we can invert our matrix
var dimetricMatrixInv = invertMatrix(dimetricMatrix); // get the invers
And now that we have the inverse matrix we can use the transform function to convert from a screen location to a block location
var screen = {x : 100, y : 200};
var blockLoc = transformPoint(screen, dimetricMatrixInv );
// result is the location of the block
The Matrix for rendering
For a bit of magic the transformation matrix dimetricMatrix can also be used by the 2D canvas, but you need to add the origin.
var m = dimetricMatrix;
ctx.setTransform(m[0], m[1], m[2], m[3], 0, 0); // assume origin at 0,0
Now you can draw a box around the block with
ctx.strokeRect(2,1,1,1); // 3rd by 2nd block 1 by 1 block wide.
The origin
I have left out the origin in all the above, I will leave that up to you to find as there is a trillion pages online about matrices as all 2D and 3D rendering use them and getting a good deep knowledge of them is important if you wish to get into computer visualization.
I'm trying to get the right tile in the isometric world by mouse position.
I've read some theads about this, but it doesn't seem to work for me.
The basic Idea is to recalculate the normal mouse coordinates to the isometric tile-coordinates.
As you can see the mouse cursor is at the tile 5/4 and the recalculation is wrong (the tile selected is 4/5). This is my Code:
var params.tx = 100, params.ty=54,
PI = 3.14152,
x1 = x_mouse - params.tx*5,
y1 = y_mouse * -2,
xr = Math.cos(PI/4)*x1 - Math.sin(PI/4)*y1,
yr = Math.sin(PI/4)*x1 + Math.cos(PI/4)*y1,
diag = (params.ty) * Math.sqrt(2),
x2 = parseInt(xr / diag)+1,
y2 = parseInt(yr * -1 / diag)+1;
The original height of a tile is 54px, but as you can see, only the border tiles show their full height. The rest of the tiles are cut by 4 pixels.
Please help me - may be my whole formula is wrong.
BACKGROUND:
The app allows users to upload a photo of themselves and then place a pair of glasses over their face to see what it looks like. For the most part, it is working fine. After the user selects the location of the 2 pupils, I auto zoom the image based on the ratio between the distance of the pupils and then already known distance between the center points of the glasses. All is working fine there, but now I need to automatically place the glasses image over the eyes.
I am using KinectJS, but the problem is not with regards to that library or javascript.. it is more of an algorithm requirement
WHAT I HAVE TO WORK WITH:
Distance between pupils (eyes)
Distance between pupils (glasses)
Glasses width
Glasses height
Zoom ratio
SOME CODE:
//.. code before here just zooms the image, etc..
//problem is here (this is wrong, but I need to know what is the right way to calculate this)
var newLeftEyeX = self.leftEyePosition.x * ratio;
var newLeftEyeY = self.leftEyePosition.y * ratio;
//create a blue dot for testing (remove later)
var newEyePosition = new Kinetic.Circle({
radius: 3,
fill: "blue",
stroke: "blue",
strokeWidth: 0,
x: newLeftEyeX,
y: newLeftEyeY
});
self.pointsLayer.add(newEyePosition);
var glassesWidth = glassesImage.getWidth();
var glassesHeight = glassesImage.getHeight();
// this code below works perfect, as I can see the glasses center over the blue dot created above
newGlassesPosition.x = newLeftEyeX - (glassesWidth / 4);
newGlassesPosition.y = newLeftEyeY - (glassesHeight / 2);
NEEDED
A math genius to give me the algorithm to determine where the new left eye position should be AFTER the image has been resized
UPDATE
After researching this for the past 6 hours or so, I think I need to do some sort of "translate transform", but the examples I see only allow setting this by x and y amounts.. whereas I will only know the scale of the underlying image. Here's the example I found (which cannot help me):
http://tutorials.jenkov.com/html5-canvas/transformation.html
and here is something which looks interesting, but it is for Silverlight:
Get element position after transform
Is there perhaps some way to do the same in Html5 and/or KinectJS? Or perhaps I am going down the wrong road here... any ideas people?
UPDATE 2
I tried this:
// if zoomFactor > 1, then picture got bigger, so...
if (zoomFactor > 1) {
// if x = 10 (for example) and if zoomFactor = 2, that means new x should be 5
// current x / zoomFactor => 10 / 2 = 5
newLeftEyeX = self.leftEyePosition.x / zoomFactor;
// same for y
newLeftEyeY = self.leftEyePosition.y / zoomFactor;
}
else {
// else picture got smaller, so...
// if x = 10 (for example) and if zoomFactor = 0.5, that means new x should be 20
// current x * (1 / zoomFactor) => 10 * (1 / 0.5) = 10 * 2 = 20
newLeftEyeX = self.leftEyePosition.x * (1 / zoomFactor);
// same for y
newLeftEyeY = self.leftEyePosition.y * (1 / zoomFactor);
}
that didn't work, so then I tried an implementation of Rody Oldenhuis' suggestion (thanks Rody):
var xFromCenter = self.leftEyePosition.x - self.xCenter;
var yFromCenter = self.leftEyePosition.y - self.yCenter;
var angle = Math.atan2(yFromCenter, xFromCenter);
var length = Math.hypotenuse(xFromCenter, yFromCenter);
var xNew = zoomFactor * length * Math.cos(angle);
var yNew = zoomFactor * length * Math.sin(angle);
newLeftEyeX = xNew + self.xCenter;
newLeftEyeY = yNew + self.yCenter;
However, that is still not working as expected. So, I am not sure what the issue is currently. If anyone has worked with KinectJS before and has an idea of what the issue may be, please let me know.
UPDATE 3
I checked Rody's calculations on paper and they seem fine, so there is obviously something else here messing things up.. I got the coordinates of the left pupil at zoom factors 1 and 2. With those coordinates, maybe someone can figure out what the issue is:
Zoom Factor 1: x = 239, y = 209
Zoom Factor 2: x = 201, y = 133
OK, since it's an algorithmic question, I'm going to keep this generic and only write pseudo code.
I f I understand you correctly, What you want is the following:
Transform all coordinates such that the origin of your coordinate system is at the zoom center (usually, central pixel)
Compute the angle a line drawn from this new origin to a point of interest makes with the positive x-axis. Compute also the length of this line.
The new x and y coordinates after zooming are defined by elongating this line, such that the new line is the zoom factor times the length of the original line.
Transform the newly found x and y coordinates back to a coordinate system that makes sense to the computer (e.g., top left pixel = 0,0)
Repeat for all points of interest.
In pseudo-code (with formulas):
x_center = image_width/2
y_center = image_height/2
x_from_zoom_center = x_from_topleft - x_center
y_from_zoom_center = y_from_topleft - y_center
angle = atan2(y_from_zoom_center, x_from_zoom_center)
length = hypot(x_from_zoom_center, y_from_zoom_center)
x_new = zoom_factor * length * cos(angle)
y_new = zoom_factor * length * sin(angle)
x_new_topleft = x_new + x_center
y_new_topleft = y_new + y_center
Note that this assumes the number of pixels used for length and width stays the same after zooming. Note also that some rounding should take place (keep everything double precision, and only round to int after all calculations)
In the code above, atan2 is the four-quadrant arctangent, available in most programming languages, and hypot is simply sqrt(x*x + y*y), but then computed more carefully (e.g., to avoid overflow etc.), also available in most programing languages.
Is this indeed what you were after?