I calculated a direction (you can call it a vector if you want, but it's really a slope...) and I want to get an x value from a function given a y value.
Basically, I am trying to draw a line from an x, y value to an x, y value and I have the direction.
Say, given a slope/direction of 1/4 (rise over run), a starting point of 200, and an ending y value of 250, how would I find x?
I know this is really basic highschool algebra, but for some reason I can't conceptualize it...
If the end points are A(x1,y1) and B(x2,y2), the slope is defined as:
m = ( y2 - y1 ) / ( x2 - x1 )
Since you do have the slope, you need to have at least three coordinates in order to be able to compute the remaining one.
From your question I assume you want to compute y2. Therefore, you need to have x1, y1, and x2.
Example:
m = 1/4
A(1,1)
B(9,y2)
---
y2 = ?
m = ( y2 - y1 ) / ( x2 - x1 )
y2 - y1 = m * ( x2 - x1 )
y2 = m * ( x2 - x1 ) + y1
y2 = 1/4 * ( 9 - 1 ) + 1
y2 = 3
Use Bresenham's line algorithm
And here are implementations in a multitude of languages (including javascript)
Bresenham's line algorithm:
void DrawLineLCD(int x1,int y1,int x2,int y2,int nState)
{
unsigned int nTmp;
unsigned int nAlt=0;
int x,y; // where is the current pixel.
int dx; // dx is the delta for x
int dy; // dy is the delta for y
int StepVal=0; // variable for figuring out when to increment the other
axis.
if (x1>x2 && y1>y2)
{
nTmp=x2;
x2=x1;
x1=nTmp;
nTmp=y2;
y2=y1;
y1=nTmp;
dx=x2-x1; // dx is the delta for x
dy=y2-y1; // dy is the delta for y
}else
{
dx=x2-x1; // dx is the delta for x
dy=y2-y1; // dy is the delta for y
if (dy<0)
{
dy=-dy;
nTmp=y2;
y2=y1;
y1=nTmp;
nAlt=1;
}else
if (dx<0)
{
dx=-dx;
nTmp=x2;
x2=x1;
x1=nTmp;
nAlt=1;
}
}
if (nAlt)
{
if(dx>=dy) // The slope is less than 45 degres
{
y=y2;
for(x=x1; x<=x2; x++)
{
// Call your function to draw a pixel here.
SetPixelLCD(x,y,nState);
StepVal+=dy;
if(StepVal>=dx) // Increment y if enough x steps
// have been taken.
{
y--;
StepVal-=dx; // Reset StepVal, but
// not to 0. This gives even slopes.
}
}
}
else // The slope is greater than 45 degrees, just like
// above, but with y instead of x.
{
x=x2;
for(y=y1; y<=y2; y++)
{
// Call your function to draw a pixel here.
SetPixelLCD(x,y,nState);
StepVal+=dx;
if(StepVal>=dy)
{
x--;
StepVal-=dy;
}
}
}
return;
}
if(dx>=dy) // The slope is less than 45 degres
{
y=y1;
for(x=x1; x<=x2; x++)
{
// Call your function to draw a pixel here.
SetPixelLCD(x,y,nState);
StepVal+=dy;
if(StepVal>=dx) // Increment y if enough x steps
// have been taken.
{
y++;
StepVal-=dx; // Reset StepVal, but
// not to 0. This gives even slopes.
}
}
}
else // The slope is greater than 45 degrees, just like
// above, but with y instead of x.
{
x=x1;
for(y=y1; y<=y2; y++)
{
// Call your function to draw a pixel here.
SetPixelLCD(x,y,nState);
StepVal+=dx;
if(StepVal>=dy)
{
x++;
StepVal-=dy;
}
}
}
return;
}
Given a point (x1,y1) and a slope m then any other point on the line is given by
y = y1 + m*(x-x1) // point is (x,y)
Related
I am trying to calculate the angle for an arrow on a ball, based on the position where it is going to.
The arrow moves, but in a total unexplainable direction, can anybody give some pointers?
Codepen available: Codepen
I added the full code on here (EDITED based on input):
I added a step to make the difference bigger for the angle calculation, not sure if that is the right way to go, but it seems a bit more functional. Plus added the +/- 90 in the angle method, but that doesnt seem to fix it. It is still feeling odd.
class Throwable {
constructor(){
this.throwObject = null;
this.canDrag = null;
this.initialDiffX = 0;
this.initialDiffY = 0;
this.previousX = 0;
this.previousY = 0;
this.intervalCounter = 0;
}
set x(input) {
this.throwObject.style.left = input + 'px';
}
set y(input) {
this.throwObject.style.top = input + 'px';
}
set rotation(input) {
this.throwObject.style.transform = `rotate(${input}deg)`;
}
init(){
this.throwObject = document.querySelector('.throwable');
this.throwObject.addEventListener('mousedown', this.activateDrag.bind(this));
this.throwObject.addEventListener('mouseup', this.deactivateDrag.bind(this));
document.addEventListener('mousemove', this.drag.bind(this));
}
activateDrag(event) {
this.canDrag = true;
this.initialDiffX = event.clientX - this.throwObject.offsetLeft;
this.initialDiffY = event.clientY - this.throwObject.offsetTop;
}
deactivateDrag() {
this.canDrag = false;
}
drag(event) {
if(this.canDrag === true) {
if(this.intervalCounter >= 30) {
this.intervalCounter = 0;
}
if(this.intervalCounter === 0) {
this.previousX = event.clientX;
this.previousY = event.clientY;
}
this.intervalCounter++;
this.y = event.clientY- this.initialDiffY;
this.x = event.clientX - this.initialDiffX;
this.rotation = this.angle(event.clientX, event.clientY, this.previousX, this.previousY);
}
}
angle(ex, ey, cx, cy) {
var dy = ey - cy;
var dx = ex - cx;
return Math.atan2(dy, dx) * 180 / Math.PI + 90;
}
// Untility
log(logObject) {
let logStr = '';
for(let key in logObject) {
logStr += `${key}: ${logObject[key]}<br>`;
}
document.getElementById('log').innerHTML = logStr;
}
}
let throwable = new Throwable();
throwable.init();
I made a mistake in comparing two different values, I fixed that, it is working way better, still have some odd behavior sometimes, seems like it doesnt know where to go in some points. But working better than before.
Maybe you have some mistakes in your angle function. This works for me:
angle(cx, cy, ex, ey) {
var dy = ey - cy ;
var dx = cx - ex ;
return Math.atan2(dx, dy) * 180 / Math.PI;
}
When you call this.angle() you give it twice this.throwObject.offset..., once directly and once via px and py:
let px = this.throwObject.offsetLeft;
let py = this.throwObject.offsetTop;
this.rotation = this.angle(this.throwObject.offsetLeft, this.throwObject.offsetTop, px, py)
That will result in dx and dy to be 0 in angle() making the result of Math.atan2() unpredictable.
I'm not sure about the rest of your code, but maybe you meant to call angle() like this:
this.rotation = this.angle(this.x, this.y, px, py);
There are a couple small issues that I can see.
First, the angle method is calculating radians in range of -180 to 180 and you want it to be 0 to 360. So after angle calculation you'll want to convert something like this:
angle(ex, ey, cx, cy) {
var dy = ey - cy;
var dx = ex - cx;
var theta = Math.atan2(dy, dx) * 180 / Math.PI;
if (theta < 0) theta += 360; // convert to [0, 360]
return theta;
}
Second, the starting angle of your element at 0 degrees is not the actual 0 degrees calculated by this method due to how js coordinates work. A quick fix is to add 90 degrees to make it match:
set rotation(input) {
this.throwObject.style.transform = `rotate(${input + 90}deg)`;
}
It's still a little janky after these conversion but I think it's a start on the right calculations. My guess is part of the issue is having such close points for calculation.
This happens because there's a difference how angles are measured between Math.atan2() and the CSS rotate transformation.
For us humans it's natural that the 12 o' clock position on an analog clock refers to the angle 0 - same for CSS rotate.
Math.atan2() however measures the angle starting from the horizontal x axis. So depending on your input coordinates it would be the 3 or 9 o' clock position.
There's an easy fix however.
After calculating the angle
Math.atan2(dy, dx) * 180 / Math.PI
just subtract 90 degrees like
Math.atan2(dy, dx) * 180 / Math.PI - 90
What happens when intervalCounter become 0? The previus point moved to the event point, so dy, dx becomes 0 and you have a jitter: -180 + 90, +180 + 90, 0 + 90 as defined in Math.atan2. After that, the previus point is fixed until intervalCounter < 30 and you have some inceasing distance between the previus and event points, so the angle is close to the expected one.
Anyway, this is a bad coordinate filter. You can improve it by implementing simple exponential filtering or by using fixed size (30 in your case) queue for event point.
All my searching comes up with more general arc/sin/cos usage or shooting to the mouse position.
I am looking to aim and fire a projectile with the keyboard and have done a lot of it from scratch, as a noob in a web class doing a project, but I am stuck on this. My current math got me to this mess in firing the shot in the direction the line is currently pointing... (code names cleaned for readability):
this.x = x + len * Math.cos(angle);
this.y = y + len * Math.sin(angle);
this.xmov = -((x + len * Math.cos(angle)) - x) / ((y + len * Math.sin(angle)) - y);
this.ymov = ((y + len * Math.sin(angle)) - y) / ((x + len * Math.cos(angle)) - x);
if (Math.abs(this.xmov) > Math.abs(this.ymov)) {
this.xmove = (this.xmov * Math.abs(this.ymov));
} else {
this.xmove = this.xmov;
}
if (Math.abs(this.ymov) > Math.abs(this.xmov)) {
this.ymove = (this.xmov * this.ymov);
} else {
this.ymove = this.ymov;
}
(And here is the full thing http://jsbin.com/ximatoq/edit. A and D to turn, S to fire (on release). Can also hold S while turning.)
... but, you'll see that it only works for 3/8's of it. What is the math to make this fire from a complete circle?
Use this as shoot function:
this.shoot = function() {
if (this.fire > 0) {
this.x = P1gun.x2;
this.y = P1gun.y2;
this.xmove = (P1gun.x2 - P1gun.x)/100;
this.ymove = (P1gun.y2 - P1gun.y)/100;
this.fire = 0;
this.firetravel = 1;
}
}
The /100 can be removed, but you have to reduce the projectile speed.
If you want to shoot gun2 change the P1gun to P2gun.
Normalising a vector.
To control the speed of something using a vector, first make the length of the vector 1 unit long (one pixel). This is commonly called normalising the vector, and sometimes it's called the unit vector. Then you can multiply that vector by any number to get the desired speed.
To normalise a vector first calculate its length, then divide it by that value.
function normalizeVector(v){
var len = Math.sqrt(v.x * v.x + v.y * v.y);
v.x /= len;
v.y /= len;
return v;
}
Trig
When you use trig to create a vector it is also a unit vector and does not need to be normalised.
function directioToUnitVector(angle){ // angle in radians
return {
x : cos(angle),
y : sin(angle)
}
Why normalise
Many many reasons, you build almost everything from unit vectors.
One example, if you have two points and want to move from one to the next at a speed of 10 pixels per second with a frame rate of 60frame per second.
var p1 = {};
var p2 = {};
p1.x = ? // the two points
p1.y = ?
p2.x = ?
p2.y = ?
// create a vector from p1 to p2
var v = {}
v.x = p2.x -p1.x;
v.y = p2.y -p1.y;
// Normalize the vector
normalizeVector(v);
var frameRate = 1/60; // 60 frames per second
var speed = 10; // ten pixels per second
function update(){
// scale vec to the speed you want. keeping the vec as a unit vec mean
// you can also change the speed, or use the time for even more precise
// speed control.
p1.x += v.x * (speed * frameRate);
p1.y += v.y * (speed * frameRate);
// draw the moving object at p1
requestAnimationFrame(update)
}
NOTE when normalizing you may get a vector that has no length. If your code is likely to create such a vector you need to check for the zero length and take appropriate action. Javascript does not throw an error when you divide by zero, but will return Infinity, with very strange results to your animations.
How to divide a line into n equal parts, eg- 5 equal parts.
For example I need to add 5 points on a straight line based on starting and ending point XY co-ordinates given below:
Starting point :
X1 : 0.27176220806794055
Y2 : 0.7258064516129032
Ending Point
X1 : 0.6303191489361702
Y2 : 0.348993288590604
How to find the coordinates value of all the points which divides the line into 5 equal parts.
Divide the distance between the start and end points by 5 for each component separately, and use this to compute all the interior points:
function divideIntoFiveSegments(startPoint, endPoint) {
let {x: x1, y: y1} = startPoint;
let {x: x2, y: y2} = endPoint;
let dx = (x2 - x1) / 5;
let dy = (y2 - y1) / 5;
let interiorPoints = [];
for (let i = 1; i < 5; i++)
interiorPoints.push({x: x1 + i*dx, y: y1 + i*dy});
return [startPoint, ...interiorPoints, endPoint];
}
This returns an array of 6 points (2 end points + 4 interior points), which defines a line with 5 segments.
You can call the function like this:
divideIntoFiveSegments({x: 0.27176220806794055, y: 0.7258064516129032}, {x: 0.6303191489361702, y: 0.348993288590604});
Have a look at the below link for the formula to divide a line in a certain ratio:
http://www.teacherschoice.com.au/Maths_Library/Analytical%20Geometry/AnalGeom_3.htm
Now in your case the ratios will be 1:5, 2:5, 3:5 and 4:5. Apply the formula and get your points.
Now to code this in JAVA/javascript you need to create a function which will take both cordinates and the ratio. This function will then return the required points. Then you can call this function for all the different ratios to get the points.
I researched google but couldn't find the keywords for search. So I ask here if my algorithm and code is efficient?
http://sketchtoy.com/66429941 (algorithm)
The algoritm is: I have four points which are: north, east, south and west of circle. I check 4 distances (distanceToNorth, distanceToEast, distanceToSouth, distanceToWest). And I find minimum of them so that is the quarter.
Here is the code but it does not seem efficient for me.
(firstQuarter is North, secondQuarter is East and so on..
note: assume that mousemove is inside the circle.
var firstQuarterX = centerX;
var firstQuarterY = centerY - radius;
var secondQuarterX = centerX + radius;
var secondQuarterY = centerY;
var thirdQuarterX = centerX;
var thirdQuarterY = centerY + radius;
var fourthQuarterX = centerX - radius;
var fourthQuarterY = centerY;
var distanceToFirst = Math.sqrt(Math.pow(x-firstQuarterX, 2) + Math.pow(y-firstQuarterY, 2));
var distanceToSecond = Math.sqrt(Math.pow(x-secondQuarterX, 2) + Math.pow(y-secondQuarterY, 2));
var distanceToThird = Math.sqrt(Math.pow(x-thirdQuarterX, 2) + Math.pow(y-thirdQuarterY, 2));
var distanceToFourth = Math.sqrt(Math.pow(x-fourthQuarterX, 2) + Math.pow(y-fourthQuarterY, 2));
var min = Math.min(distanceToFirst, distanceToSecond, distanceToThird, distanceToFourth);
var numbers = [distanceToFirst, distanceToSecond, distanceToThird, distanceToFourth];
var index = numbers.indexOf(min); // it will give 0 or 1 or 2 or 3
var quarter = index + 1;
Observe that the boundaries between your quarters lie along the lines with equations y = x and y = -x, relative to an origin at the center of the circle. You can use those to evaluate which quarter each point falls in.
If your point is (x, y), then its coordinates relative to the center of the circle are xRelative = x - centerX and yRelative = y - centerY. Then
your point is in the first (south in your code) quarter if yRelative < 0 and Math.abs(xRelative) < -yRelative
your point is in the second (east) quarter if xRelative > 0 and Math.abs(yRelative) < xRelative
your point is in the third (north) quarter if yRelative > 0 and Math.abs(xRelative) < yRelative
your point is in the fourth (west) quarter if xRelative < 0 and Math.abs(yRelative) < -xRelative
I leave it to you to determine to which quarter to assign points that fall exactly on a boundary. Also, you can implement a little decision tree based on those criteria if you prefer; that should be a little more efficient then testing each criterion in turn.
Not so sure but I think this might work. Math.atan2(CenterY - y, CenterX - x) * 180 / Math.PI gives the apparent angle between the points. Do the remaining math to figure out the quarter.
What about something like:
return x>centerX?(y>centerY?"Quad 2":"Quad 1"):(y>centerY?"Quad 3":"Quad 4");
Less graceful, more slim.
For more efficient algorithm, you can compute the quadrant just by analyzing the signs of dx + dy and dx - dy quantities (dx, dy being x, y minus centerX, centerY respectively) (I presume that as your animation shows, your quadrants are rotated by 45 degrees against 'standard' quadrants.
On a HTML canvas I have multiple points starting from 1 to N, this is basically a connect the dots application and is activated on touchstart.
There is validation so that they can only connect the dots from 1 and go to 2 (.. n). The issue is that right now is there is no validation that the line is a straight line and I am looking for an algorithm to do this, Here is what I have thought so far
For 2 points (x1,y1) to (x2,y2) get all the coordinates by finding the slope and using the formula y = mx + b
on touchmove get the x,y co-oridnates and make sure it is one of the points from the earlier step and draw a line else do not draw the line.
Is there a better way to do this or are there any different approaches that I can take ?
Edit: I originally misunderstood the question, it seems.
As far as validating the path: I think it would be easier just to have a function that determines whether a point is valid than calculating all of the values beforehand. Something like:
function getValidatorForPoints(x1, y1, x2, y2) {
var slope = (y2 - y1) / (x2 - x1);
return function (x, y) {
return (y - y1) == slope * (x - x1);
}
}
Then, given two points, you could do this:
var isValid = getValidatorForPoints(x1, y1, x2, y2);
var x = getX(), y = getY();// getX and getY get the user's new point.
if (isValid(x, y)) {
// Draw
}
This approach also gives you some flexibility—you could always modify the function to be less precise to accommodate people who don't quite draw a straight line but are tolerably close.
Precision:
As mentioned in my comment, you can change the way the function behaves to make it less exacting. I think a good way to do this is as follows:
Right now, we are using the formula (y - y1) == slope * (x - x1). This is the same as (slope * (x - x1)) - (y - y1) == 0. We can change the zero to some positive number to make it accept points "near" the valid line as so:
Math.abs((slope * (x - x1)) - (y - y1)) <= n
Here n changes how close the point has to be to the line in order to count.
I'm pretty sure this works as advertised and helps account for people's drawing the line a little crooked, but somebody should double check my math.
function drawGraphLine(x1, y1, x2, y2, color) {
var dist = Math.ceil(Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)));
var angle = Math.atan2(y2-y1, x2-x1)*180/Math.PI;
var xshift = dist - Math.abs(x2-x1);
var yshift = Math.abs(y1-y2)/2;
var div = document.createElement('div');
div.style.backgroundColor = color;
div.style.position = 'absolute';
div.style.left = (x1 - xshift/2) + 'px';
div.style.top = (Math.min(y1,y2) + yshift) + 'px';
div.style.width = dist+'px';
div.style.height = '3px';
div.style.WebkitTransform = 'rotate('+angle+'deg)';
div.style.MozTransform = 'rotate('+angle+'deg)';
}
// By Tomer Almog