Fixing simple collision detection with velocity based 2d movement - javascript

In this codePen demo you can move "player" square with arrows, place a light with space and are supposed to be stopped going over blue lines from any direction by being pushed to the opposite direction. "player" uses x and y velocity variables to create movement and multiply them by -1 (+some value) if collision detected.
The problem is that after being pushed away from the wall "player" gets stuck in a position where only moving backward from the wall is possible while appearing stuck on a perpendicular axis to that. (for example - if the wall is on top of player you can move only to bottom and not left or right after hitting the wall)
Theoretically, I would want a smooth sliding collision detection where player stuck at the wall would slowly slide down the left or right side
depending if left or right arrow pressed. (playing around I am able to achieve this but always one direction would "flow" making player slide down certain direction) I thought about using rays or some others way to detect hits, but they seem to require more computational time than just plain approach. Would appreciate any input and any recommendations of building scalable collision detections,
Here is my basic code for movement and collision detection from the demo:
let xVelocity = 0;
let yVelocity = 0;
var blockedMapGrid = [[0,30],[0,50],[0,100],[0,150],[0,200],[0,250],
[50,0],[100,0],[150,0],[200,0],[250,0],[300,0]];
var animate = function() {
if (keyState[37]) {
xVelocity -= 1;
}
if (keyState[38]) {
yVelocity += 1;
}
if (keyState[39]) {
xVelocity += 1;
}
if (keyState[40]) {
yVelocity -= 1;
}
for (var i = 0; i < blockedMapGrid.length; i++) {
if (Math.abs(player.position.x - blockedMapGrid[i][0]) +
Math.abs(player.position.y - blockedMapGrid[i][1]) < 36) {
xVelocity = -xVelocity * 1.2;
yVelocity = -yVelocity * 1.2;
console.log("Blocked by " + blockedMapGrid[i][0])
};
}
player.position.x = player.position.x + xVelocity;
player.position.y = player.position.y + yVelocity;
yVelocity *= 0.80;
xVelocity *= 0.80;
camera.position.x = player.position.x;
camera.position.y = player.position.y;
requestAnimationFrame(animate);
renderer.render(scene, camera);
};

This part of your detector is wrong:
Math.abs(player.position.x - blockedMapGrid[i][0]) +
Math.abs(player.position.y - blockedMapGrid[i][1]) < 36
Basically, here, you approximate distance from player to the point on grid by using added absolute values instead of root of sum of squares. The truth is, you don't need such a complex grid (repeating lines) and distance.
It looks like you are doing Axis-Aligned Bounding Box (AABB) detection. There is plenty of resources on internet how to optimize it.
But general approach would be like this. Your grid array should consist of boxes with (x,y,w,h) measures. Could be thin, long, square, anything.
Let's also assume your player has a bounding box (player.x, player.y, player.w, player.h), then
for (var i = 0; i < grid.length; i++) {
if (player.x < grid[i].x + grid[i].w &&
player.x + player.w > grid[i].x &&
player.y < grid[i].y + grid[i].h &&
player.y + player.h > grid[i].y) {
//collision detected! move player to previous known position
break;
}
}
You can vary, what you do when collision is detected, but finding if two boxes overlap using 4 conditions is the key here.
Update
Another problem arising from the code in the question is "bouncing" or "getting stuck" after collision is detected.
As a rule of thumb, you should never use velocity = -velocity after collision without also making sure the character gets back into the "clear", i.e. player's bounding box is not overlapping with any obstacles. Otherwise you will be stuck in infinite loop collision? -> vel = -vel, pos += vel*t -> collision -> ... with velocity bouncing from negative to positive and back without ever allowing player to get out of the wall.
The easiest way to fix it is to calculate new position of the player in temporary variables first, check if new position is not colliding, and only then make it permanent and call render(), otherwise simply ignore it and render without moving the player.
Another way is to remember last known "good" position and only give back control of the character, when it is returned to this previous position, possibly after animation or a bunch of uncontrollable moves.
There are more elaborate ways, mostly involving some kind of physics emulation to let the character bounce of multiple obstacles, assuming control inputs do not overpower inertia - think of a car on a slippery road or a boat hitting multiple trees. But either way, after you detect collision and before calling "render()" you have to place the character to a physically possible position, or it will be famously "stuck in textures".

Related

Rope physics - rope not moving correctly under gravity

I am creating a circular motion simulation, where a box of mass m hangs freely on a string. A force will then be applied to the box which will either put it in circular motion, or put it in weird motion depending on the strength of the force applied.
The rope physics works fine - at least it looks ropelike, and I used a Verlet algorithm based upon suggestions from other threads on stackoverflow and various YouTube videos after failing to apply a forces and angles based approach. This is the first time I have used this method.
The problem is that the time dependency doesn't seem to work correctly, its far too slow. I have created a stack blitz with the base code for this part of the sim. Without timeSimSpeed it looks ropey and like I would expect in real life, except far too fast.
I assumed it is something to do how I applied the force and time dependency to the sim:
processPoints2() {
for(var i = 0; i < this.points.length; i++) {
var p = this.points[i];
var timeSimSpeed = ((this.elapsedSinceFrame + this.previousElapsedSinceFrame) / 2000) * this.simulationSpeed;
if(!p.fixed) {
var vx = (p.x - p.oldx);
var vy = (p.y - p.oldy);
p.oldx = p.x;
p.oldy = p.y;
p.x += vx * timeSimSpeed;
p.y += (this.gravity + vy) * timeSimSpeed;
}
}
}
But this, logically at least, seems to make sense to me. Elasped and previousElasped are in ms and averaged which is why I have 2000 there, but even using only the current frame speed its the same outcome. I'm not familiar enough with Verlet methods to be able to work through the mathematics of whether the sticks could be restricting the motion and creating this speed issue.
Any help is much appreciated, even if it is a link to somewhere this has been addressed before that I have failed to see.
EDIT:
OK so after a bunch of comments on this I have gotten around to make some modifications. I have dropped the weird way of calculating velocity and am explicit with that now, and have also been explicit with the distance units (before it was 1 pixel per meter, but this is now defined, and I changed it to 10meters per pixel. I have also updated my stackblitz.
You will notice there are still some errors (the rope has no maximum extension and will keep stretching!) but the major one for me is that it still doesnt fall under gravity correctly...
The processing looks a lot simpler now:
processPoints2() {
for(var i = 0; i < this.points.length; i++) {
var p: point = this.points[i];
var timeSimSpeed: number = (this.elapsedSinceFrame / 1000) * this.simulationSpeed;
if(!p.fixed) {
p.vx += p.ax * timeSimSpeed;
p.vy += p.ay * timeSimSpeed;
p.x += p.vx * this.pixelsPerMeter * timeSimSpeed;
p.y += p.vy * this.pixelsPerMeter * timeSimSpeed;
}
}
}
As it just uses a classical method of calculating velocity and position.
Any help would continue to be appreciated. It has been pointed out that this isnt verlet so I have amended the title and tags to appropriately represent the question.

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

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.

How to make an object bounce of edge

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;

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

Categories

Resources