How to make an object bounce of edge - javascript

I'm making a simple game in JavaScript and using the Phaser library. I'm new to this, so hopefully this is not a silly question.
I have made it all work perfectly but I would love to know how to get the rocks to bounce of the walls, rather than go through them and appear on the other side.
It has something to do with this function:
I was told by someone to
"If it hits Width: 940 then x = 940 and you start going back 939, i--, etc. Height will continue as normal. Rather than resetting i.e shot.reset(x, y);.
If you hit the bottom or top then do the same to height, keeping width the same."
However, I am not sure how to implement this into the code. I have tried but failed :) Its very frustrating, so any help on this matter would be amazing.
Thanks.

Usually, I create a velocity vector, wich represents the "speed" of my objects.
On each frame, I add that velocity vector to the position vector. When I want my object to move to the opposite direction, I multiply my vector by -1.
Create a vector like that, and when your object collid an edge, multiply it by -1.
You can make a lot of things with this type of vector, such as smooth speed decrease, inspace-like movements etc...
e.g:
//on init
var velocity = {x: 10; y: 10};
var pos = {x: 10; y:10};
//on frame update
pos.x += velocity.x;
pos.y += velocity.y
//on edge collision
velocity.x = velocity.x * -1;
velocity.y = velocity.y * -1;

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

How to make object bounce off edge of canvas

I am trying to make a HTML/JavaScript game, but I need to make one of my objects bounce off the edge of the canvas instead of running off.
Here is my code:
http://pastebin.ca/3594744
You've got the right idea. Your object has an x & y position which is incremented/decremented each frame by the respective x or y velocity. Now all you need to do is detect when your object has collided with the bounds of the canvas, and negate the velocity in that respective direction to send the object in the opposite trajectory.
Here's some pseudocode:
// Called each frame to update the position of the object.
updatePosition():
handleCollision()
updatePosition()
// Detects a collision with a wall, calculating the bounce offset, and new velocity if applicable.
handleCollision():
// Detect collision with right wall.
if (object.x + object.width > canvas.width)
// Need to know how much we overshot the canvas width so we know how far to 'bounce'.
overshootX = (object.x + object.width) - canvas.width
object.x = canvas.width - overshootX - object.width
velocityX = -velocityX
// Repeat the same algorithm for top, left, and bottom walls.

Increasing the speed of a ball in javascript

What I'm trying to do is simply make a ball rebound from a wall. Everything works OK, except the fact I want to be able to increase the speed of movement. Literally, the speed is how much 'x-value' is added (measured in px) to the ball's current position. The thing is, when I'm increasing the var speed, the ball floats out of the bounds, because the rebounding is checked by the difference between the bound and the current position of the ball.
--------------------------------------update-----------------------------------------
I've used the technique suggested by Mekka, but still did something wrong.The ball doesn't float outside anymore, yet something "pushes it out" of the bounds for several pixels/"doesn't let the ball float several more pixels to reach the bounds".
My new code looks like this:
// the bounds-describing object
var border={
X:[8,302], // left and right borders in px
Y:[8,302], // top and bottom borders in px
indX:1, //border index for array Х
indY:0, //border index for array Y
changeInd:function(n){return this[n] = +!this[n]; } // function to change the index
};
if($("#ball").position().left + speed > border.X[1] || $("#ball").position().left + speed < border.X[0]){
var distX = "+=" + (border.X[border.indX] - $("#ball").position().left);
var distY = "-=" + ((border.X[border.indX] - $("#ball").position().left) * k);
$("#ball").css("left", distX);
$("#ball").css("top", distY);
border.changeInd("indX");
speed = -speed;
}
if($("#ball").position().top + k > border.Y[1] || $("#ball").position().top + k < border.Y[0]){
var distX = "+=" + ((border.Y[border.indY] - $("#ball").position().top) / k);
var distY = "+=" + (border.Y[border.indY] - $("#ball").position().top);
$("#ball").css("left", distX);
$("#ball").css("top", distY);
border.changeInd("indY");
k = -k;
}
Another problem is that my code's math is incorrect sometimes, the reason of which I absolutely can't figure out. To test it, try 45 degrees with different speed.
The question is: how can I improve the 'collision-checking' process or even apply some other technique to do this?
the whole code can be found here:
http://jsfiddle.net/au99f/16/
You're very close! The answer is actually hinted at in your question. You're currently using the absolute value of the distance to the boundary to determine when to change direction. This defines a "magic zone" where the ball can change direction that is about 6 pixels wide (given your speed of 3). When you increase speed to something higher (like 10), you could jump right over this magic zone.
A better way to do this would be to test if the next jump would put the ball completely outside the bounds. So this check is not based on a constant (like 3) but on the speed of the ball itself. You can also see how much the ball would have travelled out of bounds to determine how far to move the ball in the opposite direction. In other words, if your speed is 10, and the ball is 3 pixels from the right edge on step 8, then on step 9, the ball would be 7 pixels from the right edge, traveling left. Be wary of edge cases (ball could land exactly on bounds).

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?)

Categories

Resources