Find relative angle between two points - javascript

I am designing a web script to automatically create a Java file to perform autonomous actions for a robotics team based on nodes created by the player. It also features a simulation to check collision (I could use an algorithm to do this but sometimes we want it to hit the walls). The robot takes relative degrees, but atan2 gives radians on the unit circle. If I use atan, it just doesn't work right. I've tried this:
function findDegrees(node1, node2){
return Math.atan((node2.y - node1.y) / (node2.x - node1.x)) * 180 / Math.PI;
}
But it just doesn't work. This piece of code writes the data too the output. (Also, I'm following the pattern: Drive, then turn towards next node).
let theta = currentAngle - findDegrees(nextNode, twoNodes);
currentAngle += theta;
if (theta && typeof theta !== 'undefined'){
middle += `${INDENTSPACE}turn(${theta}, 1.0);\n`;
}
The way I change the x and y of the robot simulation is this:
turn(degrees, speed){
this.theta -= degrees;
}
But sometimes it goes the other way. How do I get the robot to rotate at a relative angle to the current angle where directly forward is 0°? (If you want the full code here it is.)

Related

detect collision between two circles and sliding them on each other

I'm trying to detect collision between two circles like this:
var circle1 = {radius: 20, x: 5, y: 5}; //moving
var circle2 = {radius: 12, x: 10, y: 5}; //not moving
var dx = circle1.x - circle2.x;
var dy = circle1.y - circle2.y;
var distance = Math.sqrt(dx * dx + dy * dy);
if (distance < circle1.radius + circle2.radius) {
// collision detected
}else{
circle1.x += 1 * Math.cos(circle1.angle);
circle1.y += 1 * Math.sin(circle1.angle);
}
Now when collision is detected I want to slide the circle1 from on the circle2 (circle1 is moving) like this:
--circle1---------------------------------circle2-------------------------
I could do this by updating the angle of circle1 and Moving it toward the new angle when collision is detected.
Now My question is that how can I detect whether to update/increase the angle or update/decrease the angle based on which part of circle2 circle1 is colliding with ?? (circle one comes from all angles)
I would appreciate any help
This will depend a bit on how you are using these circles, and how many will ever exist in a single system, but if you are trying to simulate the effect of two bodies colliding under gravity where one roles around to the edge then falls off (or similar under-thrust scenario), then you should apply a constant acceleration or velocity to the moving object and after you compute it's movement phase, you do a displacement phase where you take the angle to the object you are colliding with and move it back far enough in that direction to reach circle1.radius + circle2.radius.
[edit] To get that redirection after falling though (not sure if you intended this or if it's just your sketch), there is probably going to be another force at play. Most likely it will involve a "stickiness" applied between the bodies. Basically, on a collision, you need to make sure that on the next movement cycle, you apply Normal Movement, then movement towards the other body, then the repulsion to make sure they don't overlap. This way it will stick to the big circle until gravity pulls way at enough of a direct angle to break the connection.
[edit2] If you want to make this smoother and achieve a natural curve as you fall away you can use an acceleration under friction formula. So, instead of this:
circle1.x += 1 * Math.cos(circle1.angle);
circle1.y += 1 * Math.sin(circle1.angle);
You want to create velocity properties for your object that are acted on by acceleration and friction until they balance out to a fixed terminal velocity. Think:
// constants - adjust these to get the speed and smoothness you desire
var accelerationX = 1;
var accelerationY = 0;
var friction = 0.8;
// part of physics loop
circle1.velX += (accelerationX * Math.cos(circle1.angle)) - (friction * circle1.velX);
circle1.velY += (accelerationY * Math.sin(circle1.angle)) - (friction * circle1.velX);
circle1.x += circle1.velX;
circle1.y += circle1.velY;
This way, when things hit they will slow down (or stop), then speed back up when they start moving again. The acceleration as it gets back up to speed will achieve a more natural arc as it falls away.
You could get the tangent of the point of contact between both circles, which would indicate you how much to change your angle compared to the destination point (or any horizontal plane).

N-Body Gravity / Solar System Javascript Simulation

Good day, I am trying to create a simple 2D solar system model in javascript, but am having some trouble understanding how to go about calculating where planets will be for the next frame, aswell as a few other bits which I'll go into detail with soon.
After watching this very nice video and a whole bunch of his others, I made a quick MS paint image to try and simplify my situation.
With the second scene, you can see that the new position is calulated using the velocity, gravitational pull, and the angle between these two 'directions'?
I cannot get my head around how to figure this all out.
Below is a JS fiddle of my code. You'll notice I'm trying my best to use real NASA given data to keep it accurate.
You'll want to look specifically at lines 138 which is where all the calculations for its next move are made.
https://jsfiddle.net/c8eru7mk/9/
attraction: function(p2) {
// Distance to other body
var dx = p2.position.x - this.position.x;
var dy = p2.position.y - this.position.y;
var d = Math.sqrt(dx ** 2 + dy ** 2); // Possibly correct
// Force of attracrtion
this.f = G * (this.mass * p2.mass) / (d ** 2); // Possibly Correct
// Direction of force, If you read it hard enough you should be able to hear my screams of pain
// Not sure if this is correct, most likely not.
var theta = Math.atan2(dy, dx);
var fx = Math.cos(theta) * this.f;
var fy = Math.sin(theta) * this.f;
this.velocity.x += fx / this.mass;
this.velocity.y += fy / this.mass;
this.position.x += this.velocity.x;
this.position.y += this.velocity.y;
}
The problems I'm currently facing are
If I am to use NASA values, the distance between planets is so big, they won't fit on the screen, and I can't simply scale the distances down by multiplying them by 0.0002 or whatever, as that'll mess with the gravitational constant, and the simulation will be completely off.
I have no idea how to caluclate the next position and my brain has imploded several times this past week trying to attempt it several times.
I have no idea on how to check if my configuration data of planets is wrong, or if the simulation is wrong, so I'm pretty much just guessing.
This is also my first time actually coding anything more complex than a button in javascript too, so feedback on code layout and whatnot is welcome!
Many thanks
Using NASA values is not a problem when using separate coordinates for drawing. Using an appropriate linear transfomration from real coordinates to screen coordinatees for displaying does not influence the physical values and computations.
For simulating the motion of a planet with iterative updates one can assume that the gravitational force and the velocity are constant for a small portion of time dt. This factor dt is missing in your conversions from accelration to velocity and from velocity to distance. Choosing an appropriate value for dt may need some experiments. If the value is too big the approximation will be too far off from reality. If the value is too small you may not see any movement or rounding errors may influence the result.
For the beginning let us assume that the sun is always at (0,0). Also for a start let us ignore the forces between the planets. Then here are the necessary formulas for a first not too bad approximation:
scalar acceleration of a planet at position (x,y) by the gravitational force of the sun (with mass M): a = G*M/(d*d) where d=sqrt(x*x+y*y). Note that this is indepent of the planet's mass.
acceleration vector: ax = -a*x/d, ay = -a*y/d (the vector (-x,-y) is pointing towards the sun and must be brought the length a)
change of the planet's velocity (vx,vy): vx += ax*dt, vy += ay*dt
change of the planet's position: x += vx*dt, y += vy*dt

Algorithm for moving an object horizontally in javascript

I am currently working on a game using javascript and processing.js and I am having trouble trying to figure out how to move stuff diagonally. In this game, there is an object in the center that shoots other objects around it. Now I have no problem moving the bullet only vertically or only horizontally, however I am having difficulty implementing a diagonal motion for the bullet algorithm.
In terms of attempts, I tried putting on my math thinking cap and used the y=mx+b formula for motion along a straight line, but this is what my code ends up looking like:
ellipse(shuriken.xPos, shuriken.yPos, shuriken.width, shuriken.height); //this is what I want to move diagonally
if(abs(shuriken.slope) > 0.65) {
if(shuriken.targetY < shuriken.OrigYPos) {
shuriken.yPos -= 4;
} else {
shuriken.yPos += 4;
}
shuriken.xPos = (shuriken.yPos - shuriken.intercept)/shuriken.slope;
} else {
if(shuriken.targetX < shuriken.OrigXPos) {
shuriken.xPos -= 4;
} else {
shuriken.xPos += 4;
}
shuriken.yPos = shuriken.slope * shuriken.xPos + shuriken.intercept;
}
The above code is very bad and hacky as the speed varies with the slope of the line.
I tried implementing a trigonometry relationship but still in vain.
Any help/advice will be greatly appreciated!
Think of it this way: you want the shuriken to move s pixels. If the motion is horizontal, it should move s pixels horizontally; if vertical, s pixels vertically. However, if it's anything else, it will be a combination of pixels horizontally/vertically. What's the correct combination? Well, what shape do you get if you project s distance in any direction from a given point? That's right, a circle with radius s. Let's represent the direction in terms of an angle, a. So we have this picture:
How do we get the x and the y? If you notice, we have a triangle. If you recall your trigonometry, this is precisely what the sine, cosine, and tangent functions are for. I learned their definitions via the mnemonic SOHCAHTOA. That is: Sin (a) = Opposite/Hypotenuse, Cos(a) = Adjacent/Hypotenuse, Tan(a) = Opposite/Adjacent. In this case, opposite of angle a is y, and adjacent of angle a is x. Thus we have:
cos(a) = x / s
sin(a) = y / s
Solving for x and y:
x = s * cos(a)
y = s * sin(a)
So, given the angle a, and that you want to move your shuriken s pixels, you want to move it s * cos(a) horizontally and s * sin(a) vertically.
Just be sure you pass a in radians, not degrees, to javascript's Math.sin and Math.cos functions:
radians = degrees * pi / 180.0
This may be why your trigonometric solution didn't work as this has bitten me a bunch in the past.
If you know the angle and speed you are trying to move at, you can treat it as a polar coordinate, then convert to cartesian coordinates to get an x,y vector you would need to move the object by to go in that direction and speed.
If you don't know the angle, you could also come up with the vector by taking the difference in X and difference in Y (this I know you can do as you are able to calculate the slope between the 2 points). Then take the resulting vector and divide by the length of the vector to get a unit vector, which you can then scale to your speed to get a final vector in which you can move your object by.
(This is what probably what kennypu means by sticking with vectors?)

How can I determine which half of an elliptical path a point is currently on?

Here is a static frame from an atom animation I'm working on in JavaScript, modelled off this image.
Here is the code used to determine the position of an electron in its orbit based on time:
// Get position along elliptical path.
var x = Math.cos( this.timer.delta() * this.speed ) * ( this.pathWidth / 2 );
var y = Math.sin( this.timer.delta() * this.speed ) * ( this.pathHeight / 2 );
What I'd like to do is place the electron above the nucleus when on the orange part of the path, and below the nucleus during the green segment.
When this.timer.delta() == 0, the electron is at the extreme-right end, and then proceeds to travel counter-clockwise.
I'm looking for help with the following two things:
1) Finding the point in time in which the electron will be at the far left of its orbit.
2) Determining which half of the path an electron is currently on for any given time.
Ideally, the solutions should work regardless of the value of this.speed (which is number multiplier for speeding up or slowing down the animation).
It all depends on the angle - and the angle is this part in your expression:
this.timer.delta() * this.speed
So you can simply determine whether the angle is between zero and PI - and if it is - the nucleus is "in front".
Of course simply checking whether y is non-negative does the same trick.

Understanding Animation/Physics/Math Implemention with EaselJS

This is in part an EaselJS problem and in part a Physics/animation programming question.
I'm trying to learn EaselJS by studying the examples included in the EaselJS zip file. Right now, I'm looking at the SimpleTransform example,(http://bit.ly/LebvtV) where the robot rotates and fades into the background and expands towards the foreground. I find this effect really cool, and would like to learn how to achieve it. However, when I came to this set of code, I'm lost:
function tick() {
angle += 0.025;
var value = (Math.sin(angle) * 360);
bmp.setTransform (bmp.x , bmp.y , bmp.scaleX , bmp.scaleY , value/2 , bmp.skewX, bmp.skewY , bmp.regX , bmp.regY );
bmp.scaleX = bmp.scaleY = ((value)/360) + 0.25;
stage.update();
}
(For those unfamiliar with EaselJS, tick() is a function that dictates the actions on each tick, whose interval is set with setFPS. So if I've set FPS to be 20, then tick() will execute its statements 20 times in a second. I believe. And bmp here is a Bitmap object that points to the robot image.)
I've never been a wizard in Math, but I do understand the basics. I can see that angle += 0.025; is used to increased the angle variable so that the value passed into setTransform can change with time. However, I can't understand why a) 0.025 is used. b) what (Math.sin(angle) * 360) and ((value)/360) + 0.25 means, and c) why value is not just passed into setTransform, but divided by 2 (value/2).
I know it might be a challenge to explain this here, but any help is appreciated. In fact, if anyone thinks I'm a noob and needs to go study some Physics first, I'll most appreciate if someone can point me to a resource (book/url) for me to turn to.
Thanks in advance.
I can understand why you are confused. The code isn't efficient and that makes it harder to figure out what is going on. But here is the gist of it:
a) 0.025 is used because it is approximately π/125. With a Ticker speed of 25FPS, this means that the angle value will start at 0 and get to π at just about 5 seconds. π is used because Math.sin uses radians, not degrees (π radians == 180 degrees)
b) Math.sin(angle) will essentially start at 0, increase until it hits 1, decrease until it hits -1, then increase back to 0 -- all over a period of 10 seconds with sinusoidal rhythm.
(Math.sin(angle) * 360) has the same behavior as Math.sin(angle), just with a range of -360 to 360.
((value)/360) + 0.25) has the same behavior as Math.sin(angle), just with a range of -0.75 to 1.25.
c) value/2 is there so the robot only rotates 180 degrees instead of 360 degrees. I know what you are thinking -- why multiply by 360 only to divide by 2 one line later? Well, there is no reason for it really.
Here's a slightly clearer version of tick:
function tick() {
angle += Math.PI/125;
var sineValue = Math.sin(angle);
bmp.rotation = sineValue * 180;
bmp.scaleX = bmp.scaleY = sineValue + 0.25;
stage.update();
}
b) The Math.sin(angle)*360 seems like a conversion between degrees and radians.
Math.sin( x ) always evaluates to -1>=x>=1,
and therefore
Math.sin( angle ) is also always -1>=angle>=1
(we just substituted x), and
var value = Math.sin( angle ) * 360 is always -360>=value>=360.
(In the context of degrees rotated that is thus 1 whole rotation left or one whole rotation right).
We can see that the setTransform function exists as follows:
p.setTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) {}
Obviously, we can see that there is a direct connection between value & angle. What we further see is that both the transform & scaleX are again depending on value. We can pull the conclusion that each tick there will be -after some calculations- a changing transform and scaleX.
So as the variable 'value' is passed as a parameter, this means that we wish to rotate 'this' much, as much as value tells us (-360>=x>=360). That means, /2 and 0.025 is just configured like this.
Hope this is helpful :-)

Categories

Resources