2D simple ball collision vector - javascript

Trying to get two balls to collide and bounce back at appropriate angles.
When the balls collide however they get stuck together and I have no idea what I'm doing wrong here.
I'm calling this checkCollision() function within my animate function
Obviously cx is ball1 xpos, cx2 is ball2 xpos. Same for cy.
function checkCollision () {
var dx = cx2 - cx; // distance between x
var dy = cy2 - cy; // distance between y
var distance = Math.sqrt(dx * dx + dy * dy);
if (distance < (radius1 + radius2)) {
// Collision detected. Find the normal.
var normalX = dx / distance;
var normalY = dy / distance;
//find the middle point of the distance
var midpointX = (cx + cx2)/2;
var midpointY = (cy + cy2)/2;
//bounce back
cx = midpointX - radius1*normalX;
cy = midpointY - radius1*normalY;
cx2 = midpointX - radius2*normalX;
cy2 = midpointY - radius2*normalY;
var dVector = (vx - vx2) * normalX;
dVector += (vy - vy2) * normalY;
var dvx = dVector * normalX;
var dvy = dVector * normalY;
vx -= dvx;
vy -= dvy;
vx2 += dvx;
vy2 += dvy;
}
...
I've never done much/any vector work. Is there any easier way to do this?
How would I write this with angles instead?

You need to use some basic maths to detect the intersection between two circles.
A similar problem is described here:
algorithm to detect if a Circles intersect with any other circle in the same plane
There is a C# sample that could be easily adapted to Javascript.

Related

How to draw. arcs in javascript?

How to implement rounded corners in javascript?
Following is the code in C# for drawing rounded corners.
Some geometry with Paint:
0. You have a corner:
![Corner][1]
1. You know the coordinates of corner points, let it be P1, P2 and P:
![Points of corner][2]
2. Now you can get vectors from points and angle between vectors:
![Vectors and angle][3]
angle = atan(PY - P1Y, PX - P1X) - atan(PY - P2Y, PX - P2X)
3. Get the length of segment between angular point and the points of intersection with the circle.
![Segment][4]
segment = PC1 = PC2 = radius / |tan(angle / 2)|
4. Here you need to check the length of segment and the minimal length from PP1 and PP2:
![Minimal length][5]
Length of PP1:
PP1 = sqrt((PX - P1X)2 + (PY - P1Y)2)
Length of PP2:
PP2 = sqrt((PX - P2X)2 + (PY - P2Y)2)
If segment > PP1 or segment > PP2 then you need to decrease the radius:
min = Min(PP1, PP2) (for polygon is better to divide this value by 2)
segment > min ?
segment = min
radius = segment * |tan(angle / 2)|
5. Get the length of PO:
PO = sqrt(radius2 + segment2)
6. Get the C1X and C1Y by the proportion between the coordinates of the vector, length of vector and the length of the segment:
![Coordinates of PC1][6]
Proportion:
(PX - C1X) / (PX - P1X) = PC1 / PP1
So:
C1X = PX - (PX - P1X) * PC1 / PP1
The same for C1Y:
C1Y = PY - (PY - P1Y) * PC1 / PP1
7. Get the C2X and C2Y by the same way:
C2X = PX - (PX - P2X) * PC2 / PP2
C2Y = PY - (PY - P2Y) * PC2 / PP2
8. Now you can use the addition of vectors PC1 and PC2 to find the centre of circle by the same way by proportion:
![Addition of vectors][7]
(PX - OX) / (PX - CX) = PO / PC
(PY - OY) / (PY - CY) = PO / PC
Here:
CX = C1X + C2X - PX
CY = C1Y + C2Y - PY
PC = sqrt((PX - CX)2 + (PY - CY)2)
Let:
dx = PX - CX = PX * 2 - C1X - C2X
dy = PY - CY = PY * 2 - C1Y - C2Y
So:
PC = sqrt(dx2 + dy2)
OX = PX - dx * PO / PC
OY = PY - dy * PO / PC
9. Here you can draw an arc. For this you need to get start angle and end angle of arc:
![Arc][8]
Found it [here][9]:
startAngle = atan((C1Y - OY) / (C1X - OX))
endAngle = atan((C2Y - OY) / (C2X - OX))
10. At last you need to get a sweep angle and make some checks for it:
![Sweep angle][10]
sweepAngle = endAngle - startAngle
If sweepAngle < 0 then swap startAngle and endAngle, and invert sweepAngle:
sweepAngle < 0 ?
sweepAngle = - sweepAngle
startAngle = endAngle
Check if sweepAngle > 180 degrees:
sweepAngle > 180 ?
sweepAngle = 180 - sweepAngle
11. And now you can draw a rounded corner:
![The result][11]
Some geometry with c#:
private void DrawRoundedCorner(Graphics graphics, PointF angularPoint,
PointF p1, PointF p2, float radius)
{
//Vector 1
double dx1 = angularPoint.X - p1.X;
double dy1 = angularPoint.Y - p1.Y;
//Vector 2
double dx2 = angularPoint.X - p2.X;
double dy2 = angularPoint.Y - p2.Y;
//Angle between vector 1 and vector 2 divided by 2
double angle = (Math.Atan2(dy1, dx1) - Math.Atan2(dy2, dx2)) / 2;
// The length of segment between angular point and the
// points of intersection with the circle of a given radius
double tan = Math.Abs(Math.Tan(angle));
double segment = radius / tan;
//Check the segment
double length1 = GetLength(dx1, dy1);
double length2 = GetLength(dx2, dy2);
double length = Math.Min(length1, length2);
if (segment > length)
{
segment = length;
radius = (float)(length * tan);
}
// Points of intersection are calculated by the proportion between
// the coordinates of the vector, length of vector and the length of the segment.
var p1Cross = GetProportionPoint(angularPoint, segment, length1, dx1, dy1);
var p2Cross = GetProportionPoint(angularPoint, segment, length2, dx2, dy2);
// Calculation of the coordinates of the circle
// center by the addition of angular vectors.
double dx = angularPoint.X * 2 - p1Cross.X - p2Cross.X;
double dy = angularPoint.Y * 2 - p1Cross.Y - p2Cross.Y;
double L = GetLength(dx, dy);
double d = GetLength(segment, radius);
var circlePoint = GetProportionPoint(angularPoint, d, L, dx, dy);
//StartAngle and EndAngle of arc
var startAngle = Math.Atan2(p1Cross.Y - circlePoint.Y, p1Cross.X - circlePoint.X);
var endAngle = Math.Atan2(p2Cross.Y - circlePoint.Y, p2Cross.X - circlePoint.X);
//Sweep angle
var sweepAngle = endAngle - startAngle;
//Some additional checks
if (sweepAngle < 0)
{
startAngle = endAngle;
sweepAngle = -sweepAngle;
}
if (sweepAngle > Math.PI)
sweepAngle = Math.PI - sweepAngle;
//Draw result using graphics
var pen = new Pen(Color.Black);
graphics.Clear(Color.White);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.DrawLine(pen, p1, p1Cross);
graphics.DrawLine(pen, p2, p2Cross);
var left = circlePoint.X - radius;
var top = circlePoint.Y - radius;
var diameter = 2 * radius;
var degreeFactor = 180 / Math.PI;
graphics.DrawArc(pen, left, top, diameter, diameter,
(float)(startAngle * degreeFactor),
(float)(sweepAngle * degreeFactor));
}
private double GetLength(double dx, double dy)
{
return Math.Sqrt(dx * dx + dy * dy);
}
private PointF GetProportionPoint(PointF point, double segment,
double length, double dx, double dy)
{
double factor = segment / length;
return new PointF((float)(point.X - dx * factor),
(float)(point.Y - dy * factor));
}
To get points of arc you can use this:
//One point for each degree. But in some cases it will be necessary
// to use more points. Just change a degreeFactor.
int pointsCount = (int)Math.Abs(sweepAngle * degreeFactor);
int sign = Math.Sign(sweepAngle);
PointF[] points = new PointF[pointsCount];
for (int i = 0; i < pointsCount; ++i)
{
var pointX =
(float)(circlePoint.X
+ Math.Cos(startAngle + sign * (double)i / degreeFactor)
* radius);
var pointY =
(float)(circlePoint.Y
+ Math.Sin(startAngle + sign * (double)i / degreeFactor)
* radius);
points[i] = new PointF(pointX, pointY);
}
I've implemented this is javascript:
let radius = 10;
const angle =
Math.atan(p.x - p1.x, p.x - p1.x) - Math.atan(p.y - p2.y, p.x - p2.x);
let segment = radius / Math.abs(Math.tan(angle / 2));
const pp1 = Math.sqrt(Math.pow(p.x - p1.x, 2) + Math.pow(p.y - p1.y, 2));
const pp2 = Math.sqrt(Math.pow(p.x - p2.x, 2) + Math.pow(p.y - p2.y, 2));
const min = Math.min(pp1, pp2);
if (segment > min) {
segment = min;
radius = segment * Math.abs(Math.tan(angle / 2));
}
const po = Math.sqrt(Math.pow(radius, 2) + Math.pow(segment, 2));
const r = 10;
const c1x = p.x - ((p.x - p1.x) * segment) / pp1;
const c1y = p.y - ((p.y - p1.y) * segment) / pp1;
const c2x = p.x - ((p.x - p2.x) * segment) / pp2;
const c2y = p.y - ((p.y - p2.y) * segment) / pp2;
const dx = p.x * 2 - c1x - c2x;
const dy = p.y * 2 - c1y - c2y;
const pc = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
const ox = p.x - (dx * po) / pc;
const oy = p.y - (dy * po) / pc;
let startAngle = Math.atan((c1y - oy) / (c1x - ox));
let endAngle = Math.atan((c2y - oy) / (c2x - ox));
let sweepAngle = endAngle - startAngle;
if (sweepAngle < 0) {
sweepAngle = -sweepAngle;
startAngle = endAngle;
}
if (sweepAngle > 180) sweepAngle = 180 - sweepAngle;
But the issue is that the rounded corners are not getting drawn as expected!
The drawing of arc in c# is different from html canvas arc.
So how can I use the above data to draw it in html5 canvas?
To draw arcs in the html5 canvas, you can use ctx.arc(xPos, yPos, radius, startAngle, endAngle, (optional boolean, defaults to false) counterClockwise);
Documentation can be found at W3Schools.com
More general html5 canvas documentation can also be found at W3Schools.com

Does anyone know what angle it should be?

I've got myself a game, the shooting of the player is working fine but that's because I'm using an on.click event and some maths but now I'm trying to get the enemy to shoot back to my player.
me is just the enemy, so me.x and me.y is the x and the y of the enemy.
p is the player so p.x and p.yis the x and the y of the player.
We are trying to shoot from the me.x and m.y to the p.x and p.y.
As the code stands now it justs shoots randomly every second to the right.
The canvas is 500x500.
me.angle = Math.atan2(p.x, p.y) / Math.PI * 180;
me.fireBullet = function (angle) {
var b = Bullet(me.id, angle); //bullet id, with angle pack
b.x = me.x;
b.y = me.y;
}
setInterval(function () {
me.fireBullet(me.angle); //target angle attack
}
, 1000);
}
tan(angle) = y / x | arctan()
angle = arctan(x / y)
Now we only need to take the x and y of the vector going from the player to the enemy:
angle = Math.atan( (me.x - p.x) / m(e.y - p.y)) || 0;
The fix was to find the difference between x and y took me a couple of tries but its working now.
var differenceX = p.x - me.x; //players x - targets x
var differenceY = p.y - me.y; //players y - targets y
me.angle = Math.atan2(differenceY, differenceX) / Math.PI * 180

Circle/rectangle collision response

So I built some time ago a little Breakout clone, and I wanted to upgrade it a little bit, mostly for the collisions. When I first made it I had a basic "collision" detection between my ball and my brick, which in fact considered the ball as another rectangle. But this created an issue with the edge collisions, so I thought I would change it. The thing is, I found some answers to my problem:
for example this image
and the last comment of this thread : circle/rect collision reaction but i could not find how to compute the final velocity vector.
So far I have :
- Found the closest point on the rectangle,
- created the normal and tangent vectors,
And now what I need is to somehow "divide the velocity vector into a normal component and a tangent component; negate the normal component and add the normal and tangent components to get the new Velocity vector" I'm sorry if this seems terribly easy but I could not get my mind around that ...
code :
function collision(rect, circle){
var NearestX = Max(rect.x, Min(circle.pos.x, rect.x + rect.w));
var NearestY = Max(rect.y, Min(circle.pos.y, rect.y + rect.w));
var dist = createVector(circle.pos.x - NearestX, circle.pos.y - NearestY);
var dnormal = createVector(- dist.y, dist.x);
//change current circle vel according to the collision response
}
Thanks !
EDIT: Also found this but I didn't know if it is applicable at all points of the rectangle or only the corners.
Best explained with a couple of diagrams:
Have angle of incidence = angle of reflection. Call this value θ.
Have θ = normal angle - incoming angle.
atan2 is the function for computing the angle of a vector from the positive x-axis.
Then the code below immediately follows:
function collision(rect, circle){
var NearestX = Max(rect.x, Min(circle.pos.x, rect.x + rect.w));
var NearestY = Max(rect.y, Min(circle.pos.y, rect.y + rect.h));
var dist = createVector(circle.pos.x - NearestX, circle.pos.y - NearestY);
var dnormal = createVector(- dist.y, dist.x);
var normal_angle = atan2(dnormal.y, dnormal.x);
var incoming_angle = atan2(circle.vel.y, circle.vel.x);
var theta = normal_angle - incoming_angle;
circle.vel = circle.vel.rotate(2*theta);
}
Another way of doing it is to get the velocity along the tangent and then subtracting twice this value from the circle velocity.
Then the code becomes
function collision(rect, circle){
var NearestX = Max(rect.x, Min(circle.pos.x, rect.x + rect.w));
var NearestY = Max(rect.y, Min(circle.pos.y, rect.y + rect.h));
var dist = createVector(circle.pos.x - NearestX, circle.pos.y - NearestY);
var tangent_vel = dist.normalize().dot(circle.vel);
circle.vel = circle.vel.sub(tangent_vel.mult(2));
}
Both of the code snippets above do basically the same thing in about the same time (probably). Just pick whichever one you best understand.
Also, as #arbuthnott pointed out, there's a copy-paste error in that NearestY should use rect.h instead of rect.w.
Edit: I forgot the positional resolution. This is the process of moving two physics objects apart so that they're no longer intersecting. In this case, since the block is static, we only need to move the ball.
function collision(rect, circle){
var NearestX = Max(rect.x, Min(circle.pos.x, rect.x + rect.w));
var NearestY = Max(rect.y, Min(circle.pos.y, rect.y + rect.h));
var dist = createVector(circle.pos.x - NearestX, circle.pos.y - NearestY);
if (circle.vel.dot(dist) < 0) { //if circle is moving toward the rect
//update circle.vel using one of the above methods
}
var penetrationDepth = circle.r - dist.mag();
var penetrationVector = dist.normalise().mult(penetrationDepth);
circle.pos = circle.pos.sub(penetrationVector);
}
Bat and Ball collision
The best way to handle ball and rectangle collision is to exploit the symmetry of the system.
Ball as a point.
First the ball, it has a radius r that defines all the points r distance from the center. But we can turn the ball into a point and add to the rectangle the radius. The ball is now just a single point moving over time, which is a line.
The rectangle has grown on all sides by radius. The diagram shows how this works.
The green rectangle is the original rectangle. The balls A,B are not touching the rectangle, while the balls C,D are touching. The balls A,D represent a special case, but is easy to solve as you will see.
All motion as a line.
So now we have a larger rectangle and a ball as a point moving over time (a line), but the rectangle is also moving, which means over time the edges will sweep out areas which is too complicated for my brain, so once again we can use symmetry, this time in relative movement.
From the bat's point of view it is stationary while the ball is moving, and from the ball, it is still while the bat is moving. They both see each other move in the opposite directions.
As the ball is now a point, making changes to its movement will only change the line it travels along. So we can now fix the bat in space and subtract its movement from the ball. And as the bat is now fixed we can move its center point to the origin, (0,0) and move the ball in the opposite direction.
At this point we make an important assumption. The ball and bat are always in a state that they are not touching, when we move the ball and/or bat then they may touch. If they do make contact we calculate a new trajectory so that they are not touching.
Two possible collisions
There are now two possible collision cases, one where the ball hits the side of the bat, and one where the ball hits the corner of the bat.
The next images show the bat at the origin and the ball relative to the bat in both motion and position. It is travelling along the red line from A to B then bounces off to C
Ball hits edge
Ball hits corner
As there is symmetry here as well which side or corner is hit does not make any difference. In fact we can mirror the whole problem depending on which size the ball is from the center of the bat. So if the ball is left of the bat then mirror its position and motion in the x direction, and the same for the y direction (you must keep track of this mirror via a semaphore so you can reverse it once the solution is found).
Code
The example does what is described above in the function doBatBall(bat, ball) The ball has some gravity and will bounce off of the sides of the canvas. The bat is moved via the mouse. The bats movement will be transferred to the ball, but the bat will not feel any force from the ball.
const ctx = canvas.getContext("2d");
const mouse = {x : 0, y : 0, button : false}
function mouseEvents(e){
mouse.x = e.pageX;
mouse.y = e.pageY;
mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
}
["down","up","move"].forEach(name => document.addEventListener("mouse" + name, mouseEvents));
// short cut vars
var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
const gravity = 1;
// constants and helpers
const PI2 = Math.PI * 2;
const setStyle = (ctx,style) => { Object.keys(style).forEach(key=> ctx[key] = style[key] ) };
// the ball
const ball = {
r : 50,
x : 50,
y : 50,
dx : 0.2,
dy : 0.2,
maxSpeed : 8,
style : {
lineWidth : 12,
strokeStyle : "green",
},
draw(ctx){
setStyle(ctx,this.style);
ctx.beginPath();
ctx.arc(this.x,this.y,this.r-this.style.lineWidth * 0.45,0,PI2);
ctx.stroke();
},
update(){
this.dy += gravity;
var speed = Math.sqrt(this.dx * this.dx + this.dy * this.dy);
var x = this.x + this.dx;
var y = this.y + this.dy;
if(y > canvas.height - this.r){
y = (canvas.height - this.r) - (y - (canvas.height - this.r));
this.dy = -this.dy;
}
if(y < this.r){
y = this.r - (y - this.r);
this.dy = -this.dy;
}
if(x > canvas.width - this.r){
x = (canvas.width - this.r) - (x - (canvas.width - this.r));
this.dx = -this.dx;
}
if(x < this.r){
x = this.r - (x - this.r);
this.dx = -this.dx;
}
this.x = x;
this.y = y;
if(speed > this.maxSpeed){ // if over speed then slow the ball down gradualy
var reduceSpeed = this.maxSpeed + (speed-this.maxSpeed) * 0.9; // reduce speed if over max speed
this.dx = (this.dx / speed) * reduceSpeed;
this.dy = (this.dy / speed) * reduceSpeed;
}
}
}
const ballShadow = { // this is used to do calcs that may be dumped
r : 50,
x : 50,
y : 50,
dx : 0.2,
dy : 0.2,
}
// Creates the bat
const bat = {
x : 100,
y : 250,
dx : 0,
dy : 0,
width : 140,
height : 10,
style : {
lineWidth : 2,
strokeStyle : "black",
},
draw(ctx){
setStyle(ctx,this.style);
ctx.strokeRect(this.x - this.width / 2,this.y - this.height / 2, this.width, this.height);
},
update(){
this.dx = mouse.x - this.x;
this.dy = mouse.y - this.y;
var x = this.x + this.dx;
var y = this.y + this.dy;
x < this.width / 2 && (x = this.width / 2);
y < this.height / 2 && (y = this.height / 2);
x > canvas.width - this.width / 2 && (x = canvas.width - this.width / 2);
y > canvas.height - this.height / 2 && (y = canvas.height - this.height / 2);
this.dx = x - this.x;
this.dy = y - this.y;
this.x = x;
this.y = y;
}
}
//=============================================================================
// THE FUNCTION THAT DOES THE BALL BAT sim.
// the ball and bat are at new position
function doBatBall(bat,ball){
var mirrorX = 1;
var mirrorY = 1;
const s = ballShadow; // alias
s.x = ball.x;
s.y = ball.y;
s.dx = ball.dx;
s.dy = ball.dy;
s.x -= s.dx;
s.y -= s.dy;
// get the bat half width height
const batW2 = bat.width / 2;
const batH2 = bat.height / 2;
// and bat size plus radius of ball
var batH = batH2 + ball.r;
var batW = batW2 + ball.r;
// set ball position relative to bats last pos
s.x -= bat.x;
s.y -= bat.y;
// set ball delta relative to bat
s.dx -= bat.dx;
s.dy -= bat.dy;
// mirror x and or y if needed
if(s.x < 0){
mirrorX = -1;
s.x = -s.x;
s.dx = -s.dx;
}
if(s.y < 0){
mirrorY = -1;
s.y = -s.y;
s.dy = -s.dy;
}
// bat now only has a bottom, right sides and bottom right corner
var distY = (batH - s.y); // distance from bottom
var distX = (batW - s.x); // distance from right
if(s.dx > 0 && s.dy > 0){ return }// ball moving away so no hit
var ballSpeed = Math.sqrt(s.dx * s.dx + s.dy * s.dy); // get ball speed relative to bat
// get x location of intercept for bottom of bat
var bottomX = s.x +(s.dx / s.dy) * distY;
// get y location of intercept for right of bat
var rightY = s.y +(s.dy / s.dx) * distX;
// get distance to bottom and right intercepts
var distB = Math.hypot(bottomX - s.x, batH - s.y);
var distR = Math.hypot(batW - s.x, rightY - s.y);
var hit = false;
if(s.dy < 0 && bottomX <= batW2 && distB <= ballSpeed && distB < distR){ // if hit is on bottom and bottom hit is closest
hit = true;
s.y = batH - s.dy * ((ballSpeed - distB) / ballSpeed);
s.dy = -s.dy;
}
if(! hit && s.dx < 0 && rightY <= batH2 && distR <= ballSpeed && distR <= distB){ // if hit is on right and right hit is closest
hit = true;
s.x = batW - s.dx * ((ballSpeed - distR) / ballSpeed);;
s.dx = -s.dx;
}
if(!hit){ // if no hit may have intercepted the corner.
// find the distance that the corner is from the line segment from the balls pos to the next pos
const u = ((batW2 - s.x) * s.dx + (batH2 - s.y) * s.dy)/(ballSpeed * ballSpeed);
// get the closest point on the line to the corner
var cpx = s.x + s.dx * u;
var cpy = s.y + s.dy * u;
// get ball radius squared
const radSqr = ball.r * ball.r;
// get the distance of that point from the corner squared
const dist = (cpx - batW2) * (cpx - batW2) + (cpy - batH2) * (cpy - batH2);
// is that distance greater than ball radius
if(dist > radSqr){ return } // no hit
// solves the triangle from center to closest point on balls trajectory
var d = Math.sqrt(radSqr - dist) / ballSpeed;
// intercept point is closest to line start
cpx -= s.dx * d;
cpy -= s.dy * d;
// get the distance from the ball current pos to the intercept point
d = Math.hypot(cpx - s.x,cpy - s.y);
// is the distance greater than the ball speed then its a miss
if(d > ballSpeed){ return } // no hit return
s.x = cpx; // position of contact
s.y = cpy;
// find the normalised tangent at intercept point
const ty = (cpx - batW2) / ball.r;
const tx = -(cpy - batH2) / ball.r;
// calculate the reflection vector
const bsx = s.dx / ballSpeed; // normalise ball speed
const bsy = s.dy / ballSpeed;
const dot = (bsx * tx + bsy * ty) * 2;
// get the distance the ball travels past the intercept
d = ballSpeed - d;
// the reflected vector is the balls new delta (this delta is normalised)
s.dx = (tx * dot - bsx);
s.dy = (ty * dot - bsy);
// move the ball the remaining distance away from corner
s.x += s.dx * d;
s.y += s.dy * d;
// set the ball delta to the balls speed
s.dx *= ballSpeed;
s.dy *= ballSpeed;
hit = true;
}
// if the ball hit the bat restore absolute position
if(hit){
// reverse mirror
s.x *= mirrorX;
s.dx *= mirrorX;
s.y *= mirrorY;
s.dy *= mirrorY;
// remove bat relative position
s.x += bat.x;
s.y += bat.y;
// remove bat relative delta
s.dx += bat.dx;
s.dy += bat.dy;
// set the balls new position and delta
ball.x = s.x;
ball.y = s.y;
ball.dx = s.dx;
ball.dy = s.dy;
}
}
// main update function
function update(timer){
if(w !== innerWidth || h !== innerHeight){
cw = (w = canvas.width = innerWidth) / 2;
ch = (h = canvas.height = innerHeight) / 2;
}
ctx.setTransform(1,0,0,1,0,0); // reset transform
ctx.globalAlpha = 1; // reset alpha
ctx.clearRect(0,0,w,h);
// move bat and ball
bat.update();
ball.update();
// check for bal bat contact and change ball position and trajectory if needed
doBatBall(bat,ball);
// draw ball and bat
bat.draw(ctx);
ball.draw(ctx);
requestAnimationFrame(update);
}
requestAnimationFrame(update);
canvas { position : absolute; top : 0px; left : 0px; }
body {font-family : arial; }
Use the mouse to move the bat and hit the ball.
<canvas id="canvas"></canvas>
Flaws with this method.
It is possible to trap the ball with the bat such that there is no valid solution, such as pressing the ball down onto the bottom of the screen. At some point the balls diameter is greater than the space between the wall and the bat. When this happens the solution will fail and the ball will pass through the bat.
In the demo there is every effort made to not loss energy, but over time floating point errors will accumulate, this can lead to a loss of energy if the sim is run without some input.
As the bat has infinite momentum it is easy to transfer a lot of energy to the ball, to prevent the ball accumulating to much momentum I have added a max speed to the ball. if the ball moves quicker than the max speed it is gradually slowed down until at or under the max speed.
On occasion if you move the bat away from the ball at the same speed, the extra acceleration due to gravity can result in the ball not being pushed away from the bat correctly.
Correction of an idea shared above, with adjusting velocity after collision using tangental velocity.
bounciness - constant defined to represent lost force after collision
nv = vector # normalized vector from center of cricle to collision point (normal)
pv = [-vector[1], vector[0]] # normalized vector perpendicular to nv (tangental)
n = dot_product(nv, circle.vel) # normal vector length
t = dot_product(pv, circle.vel) # tangental_vector length
new_v = sum_vectors(multiply_vector(t*bounciness, pv), multiply_vector(-n*self.bounciness, nv)) # new velocity vector
circle.velocity = new_v

How to "push out "XYZ coordinates forming a 3D orbit with an offset in the middle

I have a orbit of length 200. But it is centered around a sun of radius 0 (length 0). Now I want to expand the sun to have a radius of 1 and "push" out the outer orbits as well.
The XYZ coordinates look like this:
[-6.76, 5.75, -1.06],
[-6.95, 5.54, -0.91],
[-7.13, 5.33, -0.75],
[-7.31, 5.11, -0.58]
... followed by 196 more coordinates
I tried tried a lot of things to make the circle bigger * radius and / someNumbers. To at least try to do it myself.
But i lost it when i made an if like this:
If(the x coordination > 0)
the x coordination += 1;
}
Else{
the x coordination += 1;
}
And also for Y and Z but when they came close to the 1 and -1 position of that axis they skipped to the other side.
Creating a line (with the width of 1 on both sides) of emptiness along the axis.
Result of MBo's awnser(view from above):
// arrayIndex is a number to remember at which point it is in the orbit array
satellites.forEach(function (element) {
if (element.arrayIndex>= element.satellite.coordinates.length) {
element.arrayIndex= 0;
}
var posX = element.satellite.coordinates[element.arrayIndex][0];
var posY = element.satellite.coordinates[element.arrayIndex][1];
var posZ = element.satellite.coordinates[element.arrayIndex][2];
R = Math.sqrt(posX^2 + posY^2 + posZ^2);
cf = (R + earthRadius) / R;
xnew = posX * cf;
ynew = posY * cf;
znew = posZ * cf;
// var posX = earthRadius * (element.satellite.coordinates[element.test][0] / (200 * earthRadius) * earthRadius);
// var posY = earthRadius * (element.satellite.coordinates[element.test][1] / (200 * earthRadius) * earthRadius);
// var posZ = earthRadius * (element.satellite.coordinates[element.test][2] / (200 * earthRadius) * earthRadius);
// divide by 100 to scale it down some more
element.position.x = xnew / 100;
element.position.y = ynew / 100;
element.position.z = znew / 100;
element.arrayIndex= element.arrayIndex+ 1;
});
You have orbit radius
/////////R = Sqrt(x^2 + y^2 + z^2)
Edit to avoid confusion:
R = Sqrt(x * x + y * y + z * z)
You need to modify coordinates to make orbit radius R+r. To preserve orbit form, for every point find it's R, and multiply all components by coefficient (R+r)/R
R = Sqrt(x^2 + y^2 + z^2)
cf = (R + r) / R
xnew = x * cf
ynew = y * cf
znew = z * cf

Create equilateral triangle in the middle of canvas?

I want to draw an equilateral triangle in the middle of canvas. I tried this:
ctx.moveTo(canvas.width/2, canvas.height/2-50);
ctx.lineTo(canvas.width/2-50, canvas.height/2+50);
ctx.lineTo(canvas.width/2+50, canvas.height/2+50);
ctx.fill();
But the triangle looks a bit too tall.
How can I draw an equilateral triangle in the middle of canvas?
Someone told me you have to find the ratio of the height of an equilateral triangle to the side of an equilateral triangle.
h:s
What are the two numbers?
The equation for the three corner points is
x = r*cos(angle) + x_center
y = r*sin(angle) + y_center
where for angle = 0, (1./3)*(2*pi), and (2./3)*(2*pi); and where r is the radius of the circle in which the triangle is inscribed.
You have to do it with the height of the triangle
var h = side * (Math.sqrt(3)/2);
or
var h = side * Math.cos(Math.PI/6);
So the ratio h:s is equal to:
sqrt( 3 ) / 2 : 1 = cos( π / 6 ) : 1 ≈ 0.866025
See : http://jsfiddle.net/rWSKh/2/
A simple version where X and Y are the points you want to top of the triangle to be:
var height = 100 * (Math.sqrt(3)/2);
context.beginPath();
context.moveTo(X, Y);
context.lineTo(X+50, Y+height);
context.lineTo(X-50, Y+height);
context.lineTo(X, Y);
context.fill();
context.closePath();
This makes an equilateral triange with all sides = 100. Replace 100 with how long you want your side lengths to be.
After you find the midpoint of the canvas, if you want that to be your triangle's midpoint as well you can set X = midpoint's X and Y = midpoint's Y - 50 (for a 100 length triangle).
The side lengths will not be equal given those coordinates.
The horizontal line constructed on the bottom has a length of 100, but the other sides are actually the hypotenuse of a 50x100 triangle ( approx. 112).
I can get you started with drawing an equilateral triangle but I don't have the time to get it centered.
jsFiddle
var ax=0;
var ay=0;
var bx=0;
var by=150;
var dx=bx-ax
var dy=by-ay;
var dangle = Math.atan2(dy, dx) - Math.PI / 3;
var sideDist = Math.sqrt(dx * dx + dy * dy);
var cx = Math.cos(dangle) * sideDist + ax;
var cy = Math.sin(dangle) * sideDist + ay;
var canvas = document.getElementById('equ');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(ax,ay);
ctx.lineTo(bx,by);
ctx.lineTo(cx,cy);
ctx.fill();
my code for drawing triangle also depending on direction (for lines). code is for Raphael lib.
drawTriangle(x2 - x1, y2 - y1, x2, y2);
function drawTriangle(dx, dy, midX, midY) {
var diff = 0;
var cos = 0.866;
var sin = 0.500;
var length = Math.sqrt(dx * dx + dy * dy) * 0.8;
dx = 8 * (dx / length);
dy = 8 * (dy / length);
var pX1 = (midX + diff) - (dx * cos + dy * -sin);
var pY1 = midY - (dx * sin + dy * cos);
var pX2 = (midX + diff) - (dx * cos + dy * sin);
var pY2 = midY - (dx * -sin + dy * cos);
return [
"M", midX + diff, midY,
"L", pX1, pY1,
"L", pX2, pY2,
"L", midX + diff, midY
].join(",");
}

Categories

Resources