How to detect collision between two objects at one side only? - javascript

It's like catching an object with a basket. (Bottom part of first object and Top part of second object). This is a sample of my code, but it is detecting all sides.
this.hitPocket = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright)) {
crash = false;
}
return crash;
}
UPDATED:
Hi Kenneth Mitchell De Leon, i tried your solution and changed the radius into height and width and it worked. My problem now is the basket is movable or draggable to catch the ball. (Sorry that I mentioned it late) So when i drag the basket into the ball it still catches the ball even it did not pass through the top of the basket.
function hasContact(basket, ball){
const hoop = {
topLeft: {x:basket.x+10, y: basket.y},
topRight: {x: basket.x+basket.width-10,
y: basket.y}
//not necessary if your only concern is the top panel
// botLeft: {x: basket.position.x,
// y: basket.position.y+basket.height},
// botRight: {x:basket.position.x+basket.width,
// y:basket.position.y+basket.height}
}
//determine if ball is in between top left or top right of the basket in x axis
if(ball.x > hoop.topLeft.x && ball.x+ball.width < hoop.topRight.x
//determine if the ball is in contact with top panel of basket in y axis
&& ball.y-basket.y < ball.height/2 && basket.y - ball.y < ball.height/2){
return true;
}
return false;
}

//point = {x: value, y: value} - assuming this is point object
function hasContact(point1, point2, ball){
//determine if ball is in between point1 and point2 in x axis
if(ball.position.x-ball.radius > point1.x && ball.position.x+ball.radius < point2.x
//determine if the ball is in contact in y axis
&& ball.position.y-point1.y < ball.radius && point1.y - ball.position.y < ball.radius){
return true;
}
return false;
}
//position 1 is top left
//position 2 is top right
if(hasContact(position1, position2, circle)
//use same x coords in position 1 and 2
//then add y coordinates with the ball/image height-n
//position 3 is bottom left - just low enough but not more than image/ball height
//position 5 is bottom right
&& hasContact(position3, position4, circle)){
//shot is made - do something here....
}
i am assuming something like basketball...
this will return true if the ENTIRE ball is in between left and right edge of the horizontal line, you can adjust it yourself to set it to return true if any part of the ball is in contact with the line. However it will not detect if the ball has passed from one point to another ie(goung through top to bottom);
a bit of information would be more useful...
what kind of collision detectin are you aiming for?
line and box?
line and line?
line and circle? //i assumed this one,i'll edit my answer depending on more info.
I EDITED the function. Just use it twice where the gap is not more than the image/ball height.

Related

How to detect the side on which collision occured

This is my first post so I'm trying to make my problem as clear as possible. I'm making a game and I want to improve my collision detection. This is because I want to check what side is being hit and stop the player from moving past it without using something general like if(collision(player, enemy)) player.x = enemy.x - player.w(width) because if the player were to collide with the top it wouldn't keep the player on top.
In the code it checks if any one of the statements is true and then returns it but it doesn't tell me which statement was the one that was equal to true so I can stop the player from moving accordingly, if that makes sense. If you have a more efficient collision detection for me to use it would be greatly appreciated.
I've already tried to make a position variable to be equal to whatever side gets collided into and then stop the player from moving past it but it only works for the left side and won't let my player jump over the enemy or block.
function collision(object1, object2) {
return !(
object1.x > object2.x + object2.w ||
object1.x + object1.w < object2.x ||
object1.y > object2.y + object2.h ||
object1.y + object1.h < object2.y
)
}
//Only works for the left side
if(collision(player, enemy)) player.x = enemy.x - player.w
I expect it to be able to tell me what side is being collided into and then either stop the player from moving past/into it and for the player to be able to be on top of the block/enemy without just being pushed to the left.
You'll want to calculate the distance between the x's and y's and also use the minimum distance that they could be colliding along each axis to find the depth along both axes. Then you can pick the smaller depth and move along that one. Here's an example:
if(collision(player, enemy)){
// Most of this stuff would probably be good to keep stored inside the player
// along side their x and y position. That way it doesn't have to be recalculated
// every collision check
var playerHalfW = player.w/2
var playerHalfH = player.h/2
var enemyHalfW = enemy.w/2
var enemyHalfH = enemy.h/2
var playerCenterX = player.x + player.w/2
var playerCenterY = player.y + player.h/2
var enemyCenterX = enemy.x + enemy.w/2
var enemyCenterY = enemy.y + enemy.h/2
// Calculate the distance between centers
var diffX = playerCenterX - enemyCenterX
var diffY = playerCenterY - enemyCenterY
// Calculate the minimum distance to separate along X and Y
var minXDist = playerHalfW + enemyHalfW
var minYDist = playerHalfH + enemyHalfH
// Calculate the depth of collision for both the X and Y axis
var depthX = diffX > 0 ? minXDist - diffX : -minXDist - diffX
var depthY = diffY > 0 ? minYDist - diffY : -minYDist - diffY
// Now that you have the depth, you can pick the smaller depth and move
// along that axis.
if(depthX != 0 && depthY != 0){
if(Math.abs(depthX) < Math.abs(depthY)){
// Collision along the X axis. React accordingly
if(depthX > 0){
// Left side collision
}
else{
// Right side collision
}
}
else{
// Collision along the Y axis.
if(depthY > 0){
// Top side collision
}
else{
// Bottom side collision
}
}
}
}
Working example
Here's a working example that you can play around with. Use the arrow keys to move the player around.
player = {
x: 9,
y: 50,
w: 100,
h: 100
}
enemy = {
x: 100,
y: 100,
w: 100,
h: 100
}
output = document.getElementById("collisionType");
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d")
function collision(object1, object2) {
return !(
object1.x > object2.x + object2.w ||
object1.x + object1.w < object2.x ||
object1.y > object2.y + object2.h ||
object1.y + object1.h < object2.y
)
}
function draw() {
ctx.clearRect(0, 0, 400, 400)
ctx.lineWidth = "5"
ctx.beginPath();
ctx.strokeStyle = "red";
ctx.rect(player.x, player.y, player.w, player.h);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = "blue";
ctx.rect(enemy.x, enemy.y, enemy.w, enemy.h);
ctx.stroke();
}
function handleCollision() {
if (collision(player, enemy)) {
var playerHalfW = player.w / 2
var playerHalfH = player.h / 2
var enemyHalfW = enemy.w / 2
var enemyHalfH = enemy.h / 2
var playerCenterX = player.x + player.w / 2
var playerCenterY = player.y + player.h / 2
var enemyCenterX = enemy.x + enemy.w / 2
var enemyCenterY = enemy.y + enemy.h / 2
// Calculate the distance between centers
var diffX = playerCenterX - enemyCenterX
var diffY = playerCenterY - enemyCenterY
// Calculate the minimum distance to separate along X and Y
var minXDist = playerHalfW + enemyHalfW
var minYDist = playerHalfH + enemyHalfH
// Calculate the depth of collision for both the X and Y axis
var depthX = diffX > 0 ? minXDist - diffX : -minXDist - diffX
var depthY = diffY > 0 ? minYDist - diffY : -minYDist - diffY
// Now that you have the depth, you can pick the smaller depth and move
// along that axis.
if (depthX != 0 && depthY != 0) {
if (Math.abs(depthX) < Math.abs(depthY)) {
// Collision along the X axis. React accordingly
if (depthX > 0) {
output.innerHTML = "left side collision"
} else {
output.innerHTML = "right side collision"
}
} else {
// Collision along the Y axis.
if (depthY > 0) {
output.innerHTML = "top side collision"
} else {
output.innerHTML = "bottom side collision"
}
}
}
} else {
output.innerHTML = "No collision"
}
}
keyStates = []
function handleKeys() {
if (keyStates[39]) {
player.x += 2 //Move right
} else if (keyStates[37]) {
player.x -= 2 //Move left
}
if (keyStates[38]) {
player.y -= 2 //Move up
}
if (keyStates[40]) {
player.y += 2 //Move down
}
}
function main() {
handleKeys();
draw();
handleCollision();
window.requestAnimationFrame(main);
}
window.onkeydown = function(e) {
keyStates[e.keyCode] = true
}
window.onkeyup = function(e) {
keyStates[e.keyCode] = false
}
main();
<h2 id="collisionType"></h2>
<canvas id="canvas" width='300' height='300'></canvas>
Reacting to the collision
Now that you know the side the collision happened on, it should be fairly trivial to decide how to react. It would be very similar to what you are currently doing for the left side just flip some signs around and change the axis.
Other Considerations
You may want to take into account your player's velocity (if it has one) otherwise the detection may fail.
If the player's velocity is too high, it might 'tunnel' through the enemy and no collision will be detected.
The player's movement can also look jittery if the velocity is not stopped upon collision
Can your objects rotate or have more than 4 sides? If so, you'll probably want to use another method as described below.
Here's a good answer to another post that talks in depth about collision engines
Other Methods
As for other collision detection methods, there's quite a few but one that comes to mind is Separating Axis Theorem which is a little more complex than what you have but will work with more complex convex shapes and rotation. It also tells you the direction and distance needed to move to resolve the collision. Here's a site that has interactive examples and goes in-depth on the subject. It doesn't appear to give a full implementation but those can be found other places.

Make Chart.js Radar labels clickable

Has anyone managed to make the labels around the Chart.js Radar perimeter clickable?
There doesn't seem to be an immediately obvious solution.
I came up with a solution for this for version 2.8.0 by copying the label position calculations from the RadialLinear scale into an event handler.
document.getElementById("myChart").onclick = function (e) {
var helpers = Chart.helpers;
var scale = myRadarChart.scale;
var opts = scale.options;
var tickOpts = opts.ticks;
// Position of click relative to canvas.
var mouseX = e.offsetX;
var mouseY = e.offsetY;
var labelPadding = 5; // number pixels to expand label bounding box by
// get the label render position
// calcs taken from drawPointLabels() in scale.radialLinear.js
var tickBackdropHeight = (tickOpts.display && opts.display) ?
helpers.valueOrDefault(tickOpts.fontSize, Chart.defaults.global.defaultFontSize)
+ 5: 0;
var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
for (var i = 0; i < scale.pointLabels.length; i++) {
// Extra spacing for top value due to axis labels
var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
// get label size info.
// TODO fix width=0 calc in Brave?
// https://github.com/brave/brave-browser/issues/1738
var plSize = scale._pointLabelSizes[i];
// get label textAlign info
var angleRadians = scale.getIndexAngle(i);
var angle = helpers.toDegrees(angleRadians);
var textAlign = 'right';
if (angle == 0 || angle == 180) {
textAlign = 'center';
} else if (angle < 180) {
textAlign = 'left';
}
// get label vertical offset info
// also from drawPointLabels() calcs
var verticalTextOffset = 0;
if (angle === 90 || angle === 270) {
verticalTextOffset = plSize.h / 2;
} else if (angle > 270 || angle < 90) {
verticalTextOffset = plSize.h;
}
// Calculate bounding box based on textAlign
var labelTop = pointLabelPosition.y - verticalTextOffset - labelPadding;
var labelHeight = 2*labelPadding + plSize.h;
var labelBottom = labelTop + labelHeight;
var labelWidth = plSize.w + 2*labelPadding;
var labelLeft;
switch (textAlign) {
case 'center':
var labelLeft = pointLabelPosition.x - labelWidth/2;
break;
case 'left':
var labelLeft = pointLabelPosition.x - labelPadding;
break;
case 'right':
var labelLeft = pointLabelPosition.x - labelWidth + labelPadding;
break;
default:
console.log('ERROR: unknown textAlign '+textAlign);
}
var labelRight = labelLeft + labelWidth;
// Render a rectangle for testing purposes
ctx.save();
ctx.strokeStyle = 'red';
ctx.lineWidth = 1;
ctx.strokeRect(labelLeft, labelTop, labelWidth, labelHeight);
ctx.restore();
// compare to the current click
if (mouseX >= labelLeft && mouseX <= labelRight && mouseY <= labelBottom && mouseY >= labelTop) {
alert(scale.pointLabels[i]+' clicked');
// Break loop to prevent multiple clicks, if they overlap we take the first one.
break;
}
}
};
JSFiddle here:
https://jsfiddle.net/simoncoggins/7r08uLk9/
The downside of this approach is it that it will break if the core labelling implementation changes in the future. It would be better if the library separated the calculation of label position from its rendering and started exposing the position info via the API. Then this solution could be greatly simplified and would be more robust to library changes.
I've opened a ticket offering to make that change here:
https://github.com/chartjs/Chart.js/issues/6549
Please comment on that issue if it would be useful to you.
Thanks Pogrindis. Answer here works for Chart.js v2.1: Chart.js click on labels, using bar chart
To make that work for Chart.js v5.0+, add the following function back into the Chart.js code.
LinearRadialScale = Chart.LinearScaleBase.extend({...})
getValueCount: function() {
return this.chart.data.labels.length;
}

getting any overlaps even when rotated

I have been learning about konva and html canvas and with the help of the community here I have a canvas with draggable shapes which stay in the bounds of the stage even when rotated.
Also, my konva code is detecting intersections in dragboundfunc and setting strokeEnabled to true if a intersection is detected. I was using my own collision detection code/function until yesterday but because I wasn't getting correct detection results when shapes had been rotated I changed my code to put the shape being dragged in a tempLayer to enable getIntersection to work during dragBoundFunc hoping that would fix it but it didn't.
My problem is I cannot get correct collision detection even with getIntersection rather than my own collision detection code and have spent since last night trying. I can get it detecting collision fine if the shape rotation is 0 using the code below which is my shapes dragBoundFunc.
I know I can't be far off but I'm also at a loss. I also know the part of my code where I set collisionz is probably the wrong way of going about this even though it works for 0 degrees rotation but I have left it in to show what I have tried and that I am trying.
Does anyone know the answer to help me on my way with Konva please?
function theDragFunc(pos) {
var thisRect;
if(parseInt(this.getClientRect().width) != parseInt(this.width())){
if(userRotation == 90 || userRotation == 270)
thisRect = {x: this.x(), y: this.y(), width: this.getClientRect().height, height: this.getClientRect().width};
else
thisRect = {x: this.x(), y: this.y(), width: this.getClientRect().width, height: this.getClientRect().height};
console.log("must have changed userRotation = "+userRotation);
}
else{
thisRect = {x: this.x(), y: this.y(), width: this.width(), height: this.height()};
console.log("must not have changed userRotation = " +userRotation);
}
isCollision = false;
// copy the boundary rect into a testRect which defines the extent of the dragbounds without
// accounting for the width and height of dragging rectangle.
// This is changed below depending on rotation.
var testRect={
left: boundary.x,
top: boundary.y,
right: boundary.x + boundary.width,
bottom: boundary.y + boundary.height
};
// the userRotation value is calculated in the rotation button onclick
// to be one of 0, 90, 180, 270
switch (userRotation){
case 0: // for 0 degrees compute as per a normal bounds rect
testRect.right = testRect.right - thisRect.width;
testRect.bottom = testRect.bottom - thisRect.height;
break;
case 90: // for 90 degs we have to modify the test boundary left and bottom
testRect.left = testRect.left + thisRect.height;
testRect.bottom = testRect.bottom - thisRect.width;
break;
case 180: // for 180 degs we have to modify the test boundary left and top
testRect.left = testRect.left + thisRect.width;
testRect.top = testRect.top + thisRect.height;
break;
case 270: // for 270 degs we have to modify the test boundary right and top
testRect.right = testRect.right - thisRect.height;
testRect.top = testRect.top + thisRect.width;
break;
}
// get new pos as: if pos inside bounday ranges then use it, otherwise user boundary
var newX = (pos.x < testRect.left ? testRect.left : pos.x);
// looking at the far x pos we need to consider width of the dragging rect...
newX = (newX > testRect.right ? testRect.right : newX);
// get new pos as: if pos inside bounday ranges then use it, otherwise user boundary
var newY = (pos.y < testRect.top ? testRect.top : pos.y);
// looking at the far y pos we need to consider height of the dragging rect...
newY = (newY > testRect.bottom ? testRect.bottom : newY);
var collisionz = stage.getIntersection({x:newX+this.getClientRect().width,y:newY}, ".rect");
if(!collisionz)collisionz = stage.getIntersection({x:newX,y:newY}, ".rect");
else if(!collisionz)collisionz = stage.getIntersection({x:newX,y:newY+this.getClientRect().height}, ".rect");
else if(!collisionz)collisionz = stage.getIntersection({x:newX,y:newY+this.getClientRect().height/2}, ".rect");
else if(!collisionz)collisionz = stage.getIntersection({x:newX+this.getClientRect().width,y:newY+this.getClientRect().height/2}, ".rect");
else if(!collisionz)collisionz = stage.getIntersection({x:newX + this.getClientRect().height/2,y:newY + this. getClientRect().height}, ".rect");
if(!collisionz)collisionz = stage.getIntersection({x:newX + this.getClientRect().width,y:newY + this.getClientRect().height}, ".rect");
var search_term = 'funcRect';
if(collisionz && collisionz != this){
console.log("INTERSECTION detected"+collisionz.getName());
isCollision = true;
}
else
isCollision = false;
if(!isCollision && this.getStrokeEnabled())
{
this.setStrokeEnabled(false);
layer.draw();
}
else if(isCollision && !this.getStrokeEnabled())
{
this.setStrokeWidth(2);
this.setStroke('black');
this.setStrokeEnabled(true);
layer.draw();
}
return {
x: newX,
y: newY
}
}

JavaScript collision detection with objects in a multi-dimensional array

I'm currently coding a Pac-man clone with p5.js, and have ran into an issue. I have created a function which draws the map by using a multi-dimensional array, drawing a wall block where a 1 is, and nothing where a 0 is.
This works fine, however i'm struggling to detect collision between the player and the walls. I have tried to use a for loop to go through the array, checking the x and y co-ordinates to see if there is a collision, however it doesn't register at all.This is the code i have used to detect collision:
for(i=0;i<walls.length;i++){
walls[i].draw();
if(player.x > walls[i].x && player.x < walls[i].x + gridsize && player.y > walls[i].y && player.y < walls[i].y + gridsize){
console.log('collision')
}
}
I can't see where the issue is here, as it seems to have worked in other programs.
This runs in the Draw() function, meaning it loops 30 times a second.
This is the full code, incase the issue lies elsewhere:
var gridsize = 20;
var walls = [];
var dots = [];
var player;
var score =0;
var maps = [[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,0,1,1,1,1,1,1,0,1,1,0,1],
[1,0,1,1,0,0,0,0,0,0,0,0,1,1,0,1],
[1,0,0,0,0,1,1,1,1,1,1,0,0,0,0,1],
[1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1],
[1,0,0,0,0,1,1,0,0,1,1,0,0,0,0,1],
[1,0,1,0,0,1,0,0,0,0,1,0,0,1,0,1],
[1,0,1,0,0,1,0,0,0,0,1,0,0,1,0,1],
[1,0,1,0,0,1,1,1,1,1,1,0,0,1,0,1],
[1,0,1,0,0,0,0,2,0,0,0,0,0,1,0,1],
[1,0,1,1,1,0,1,1,1,1,0,1,1,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,1,1,1,1,1,1,1,1,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]];
function setup(){
createCanvas(320,320);
frameRate(30);
createMap();
}
function draw(){
background(51);
for(i=0;i<walls.length;i++){
walls[i].draw();
if(player.x > walls[i].x && player.x < walls[i].x + gridsize && player.y
> walls[i].y && player.y < walls[i].y + gridsize){
console.log('collision')
}
}
fill('white');
text('Score: ' + score, 5,10);
for(i=0;i<dots.length;i++){
if(player.x == dots[i].x && player.y == dots[i].y && dots[i].collect ==
false){
dots[i].collect = true;
score++;
}
dots[i].draw();
}
player.update();
player.draw();
}
function Block(x,y){
this.x = x;
this.y = y;
this.draw = function(){
fill('black');
rect(this.x,this.y,gridsize,gridsize);
}
}
function Dot(x,y){
this.x = x;
this.y = y;
this.collect = false;
this.draw = function(){
if(!this.collect){
fill('yellow');
ellipse(this.x+gridsize/2,this.y+gridsize/2,gridsize/3,gridsize/3);
}else if(this.collect){
noFill();
noStroke();
ellipse(this.x+gridsize/2,this.y+gridsize/2,gridsize/3,gridsize/3);
}
}
}
function Player(x,y){
this.x = x;
this.y = y;
this.update = function(){
if(keyIsDown(UP_ARROW) && frameCount%5 == 0){
player.y -= gridsize;
}
if(keyIsDown(DOWN_ARROW) && frameCount%5 == 0){
player.y += gridsize;
}
if(keyIsDown(LEFT_ARROW) && frameCount%5 == 0){
player.x -= gridsize;
}
if(keyIsDown(RIGHT_ARROW) && frameCount%5 == 0){
player.x += gridsize;
}
}
this.draw = function(){
fill('blue');
ellipse(this.x+gridsize/2,this.y+gridsize/2,gridsize/1.2,gridsize/1.2);
}
}
function createMap(){
for(i=0;i<maps.length;i++){
for(j=0;j<maps[i].length;j++){
if (maps[i][j] == 1){
walls.push(new Block(j*gridsize,i*gridsize));
}else if(maps[i][j] == 0){
dots.push(new Dot(j*gridsize,i*gridsize))
}else if(maps[i][j] = 2){
player = new Player(j*gridsize,i*gridsize)
}
}
}
}
I presume the issue lies with the fact that the walls are stored in an array, however i have done very similar programs in which the same code works.
PacMan controls
The best way to check for this type of map is to use the player's input.
The player must line up with the walls so assuming the player position is relative to the top left and the player is one map unit wide and deep.
Key input requests a direction to move dx, dy hold the directions which could be more than one at a time. If dx or dy are not 0 then first check if the player is lined up with a passage, if so then check if a block is in the direction of travel. If the player is not lined up or blocked set the movement var to 0
After checking both x and y directions, then if dx or dy have a value then that must be a valid move.
Code changes
Remove the player collision checking code from the main loop and call the player update function with the current map as the 2D original.
player.update(maps); // move the player
Change the Player and update function
function Player(x,y){
this.x = x;
this.y = y;
var dx = 0; // hold current movement
var dy = 0;
const speed = 1; // per Frame pixel speed best as an integer (whole number) and evenly divisible into gridSize
// need the map so that must be passed to the update function
this.update = function(map){
// assuming keys are held to move up to stop
dx = 0; // stop by default
dy = 0;
if (keyIsDown(UP_ARROW)) { dy = -speed }
if (keyIsDown(DOWN_ARROW)) { dy = speed }
if (keyIsDown(LEFT_ARROW)) { dx = -speed }
if (keyIsDown(RIGHT_ARROW)){ dx = speed }
// get player map coords
var x = Math.floor(this.x / gridSize); // get map coord
var y = Math.floor(this.y / gridSize); // get map coord
// the two if statement are best aas function
// so you can select which one to call first. Depending on the latest
// new keys down and if the result allows movement in that
// direction then set the other direction to zero.
if (dy !== 0) { // is moving up or down?
if (this.y % gridsize === 0) { // only if lined up
if (dy > 0){ // is moving down
if (map[y + 1][x] === 1) { // down blocked
dy = 0;
}
}else if (map[y - 1][x] === 1) { // up blocked
dy = 0;
}
} else { // block move if not lined up with passage
dy = 0;
}
}
if(dx !== 0){ // is moving left or right?
if (this.x % gridsize === 0) { // only if lined up
if (dx > 0) { // is moving right
if (map[y][x + 1] === 1) { // right blocked
dx = 0;
}
} else if (map[y][x - 1] === 1) { // left blocked
dx = 0;
}
} else { // block move if not lined up with passage
dx = 0;
}
}
// could have two moves, but can only move left right or up down
// you need to add some input smarts to pick which one
// this just favours up down
if(dy !== 0) { dx = 0 };
// only valid moves will come through the filter above.
// so move the player.
this.x += dx;
this.y += dy;
}
Adding more smarts
Note I have changed the way the player moves, I set a speed per frame (1 pixel) that must be an even divisor of gridSize.
The code above is the simplest implementation. This type of games needs some extra smarts in controls. You should check in the direction of the newest key down. Ie if the player traveling down and right is pressed then moving right should have priority. If player moving right and left is pressed then you should move left, not keep moving right.
Extras
While looking at this question I wanted to visualize the map. Maps as arrays are painful to create and modify, and very hard to find mistakes in. Much easier as a a set of strings that gets converted to an array at run time.
As i have done the conversion no point wasting it. maps is identical to the original array but now easier to read and change.
const maps = [
"################",
"# #",
"# ## ###### ## #",
"# ## ## #",
"# ###### #",
"#### ####",
"# ## ## #",
"# # # # # #",
"# # # # # #",
"# # ###### # #",
"# # 2 # #",
"# ### #### ### #",
"# #",
"# ######## #",
"# #",
"################"
].map(row => row.split("").map(c => c === "#" ? 1 : c === " " ? 0 : 2));
I'm not quite sure why you're using rectangle-rectangle collision detection when you could just use grid-based collision detection. You could just use the array directly.
But since you are using rectangle-rectangle collision, this line looks a little bit off:
if(player.x > walls[i].x && player.x < walls[i].x + gridsize && player.y > walls[i].y && player.y < walls[i].y + gridsize){
You're checking whether the left edge of the player is inside the wall and whether the top edge of the player is inside the wall. But you aren't detecting the other edges. Usually you'd want to do something like this:
if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
Notice how this if statement checks all of the edges, not just the top and left. But like I said, you might be better off just using grid collision detection, since you already have a grid of walls.
Shameless self-promotion: here is a tutorial on collision detection. It's written for Processing, but everything should translate pretty directly to P5.js.
if the player is not sprite here then point-in-rect collision detection will be appropriate here.
// point in rect collision detection
function pointInRect (x, y, rect) {
return inRange(x, rect.x, rect.x + gridsize) &&
inRange(y, rect.y, rect.y + gridsize);
}
// check a value is in range or not
function inRange (value, min, max) {
return value >= Math.min(min, max) && value <= Math.max(min, max);
}
// checking player is hitting the wall or not
if(pointInRect(player.x,player.y,walls[i].x,walls[i].y))
{
console.log('collision')
}

wall collision detection with html5 canvas [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am making a game and there is a wall that I don't want the player to pass. I am using html5 canvas and have a player object to hold the x and y values. The wall is at x: 650 and y: 0. Since the player is 20x20 pixels when its x coordinate is 630, it touches the wall.
if(player.x > 630 && player.y <= 500) {
player.x = 630;
}
What is wrong with this code? I appreciate any help!
Answer
The code you have give is OK, there is nothing wrong with it. So I suspect the problem is elsewhere in the code, most likely in the movement code. If you are moving the player after the wall test and then display it, the player may start to creep into the wall, but without the rest of the code it is hard to know what is wrong with your code.
I have included more details on the correct way to do collision tests as there are two answers showing only a partial solution. It is there as a general guide to collision testing and may not be directly applicable to the question.
Inter frame movement
The correct way to reflect an object from a surface.
You must take into account that the ball is moving between frames and that the collision may have happened at any time during the previous frame. The ball's distance from the wall after the collision is dependent on when during the previous frame it hit the wall. This is important if the ball moves slowly or quickly.
var dx = 10; // delta x velocity of object in pixels
var wx = 10; // width of object in pixels
var px = 90; // position of object in pixels
var wallX = 105; // position of wall
px += dx; // move the ball. Its position is now 100.
// its right side is at px + wx = 110.
// test if it has it the wall
if(px+wx > wallX){
dx = -dx; // reflect delta x
// The object is 5 pixel into the wall.
// The object has hit the wall some time during the last frame
// We need to adjust the position as the ball may have been
// traveling away from the wall for some time during the last frame.
var dist = (px+wx)-wallX; // get the distance into the wall
px -= dist*2; // the object hit the wall at position 95 and has been
// traveling away since then so it is easy to just
// subtract 2 times the distance the ball entered the wall
// the above two lines can be done in one
// px -= ((px+wx)-wallX)*2;
}
Why it matters
Below is a simulation of a ball bouncing inside the canvas.
To illustrate that the ball is moving between frames it has been motion blurred to show its motion between frames. Please note this is not the perfect solution as the bounce is assumed to occur while the ball is in linear motion while infact it is in freefall and under constant acceleration. But it still conserves energy.
In the correct test the height the ball bounces back to, stays around the same over time. No energy is lost or gained.
Right click to turn off the inter frame adjustment and you will notice that the ball begins to decrease its height each frame. This is because at each collision the ball loses a little energy because it motion during the previous frame is not taken into account when positioning it after the collision test. It will settle down to a constant rate when the collision occurres at precisely the frame time. When that will be is very hard to determine in advance.
Left click to slow the simulation frame rate, left click again to return to normal.
The code below is not really part of the answer, it is there to demonstrate the effect of not correctly adjusting the position during collision test on the overall accuracy of the simulation.
// helper functions. NOT part of the answer
var canvas = document.getElementById("canV");
var ctx = canvas.getContext("2d");
var mouseButton = 0;
canvas.addEventListener('mousedown',function(event){mouseButton = event.which;});
canvas.addEventListener('mouseup' ,function(){mouseButton = 0;});
canvas.addEventListener("contextmenu", function(e){ e.preventDefault();}, false);
var currentSurface = ctx;
var createImage = function (w, h) {// create an canvas image of size w,h and attach context 2d
var image = document.createElement("canvas");
image.width = w;
image.height = h !== undefined?h:w;
currentSurface = image.ctx = image.getContext("2d");
return image;
}
var setColour = function (fillC, strokeC, lineW) {
currentSurface.fillStyle = fillC !== undefined ? fillC : currentSurface.fillStyle;
currentSurface.strokeStyle = strokeC !== undefined ? strokeC : currentSurface.strokeStyle;
currentSurface.lineWidth = lineW !== undefined ? lineW : currentSurface.lineWidth;
}
var circle = function(x,y,r,how){
currentSurface.beginPath();
currentSurface.arc(x,y,r,0,Math.PI*2);
how = how.toLowerCase().replace(/[os]/g,"l"); // how to draw
switch(how){
case "f": // fill
currentSurface.fill();
break;
case "l":
currentSurface.stroke();
break;
case "lf":
currentSurface.stroke();
currentSurface.fill();
break;
case "fl":
currentSurface.fill();
currentSurface.stroke();
break;
}
}
function createGradImage(size,col1,col2){
var image = createImage(size);
var g = currentSurface.createLinearGradient(0,0,0,currentSurface.canvas.height);
g.addColorStop(0,col1);
g.addColorStop(1,col2);
currentSurface.fillStyle = g;
currentSurface.fillRect(0,0,currentSurface.canvas.width,currentSurface.canvas.height);
return image;
}
function createColouredBall (ballR,col) {
var ball = createImage(ballR*2);
var unit = ballR/100;
setColour("black");
circle(ballR,ballR,ballR,"f");
setColour("hsl("+col+",100%,30%)");
circle(ballR-unit*3,ballR-unit*3,ballR-unit*7,"f");
setColour("hsl("+col+",100%,50%)");
circle(ballR-unit*10,ballR-unit*10,ballR-unit*16,"f");
setColour("White");
circle(ballR-unit*50,ballR-unit*50,unit*16,"f");
return ball;
}
//===================================
// _
// /_\ _ _ ____ __ _____ _ _
// / _ \| ' \(_-< V V / -_) '_|
// /_/ \_\_||_/__/\_/\_/\___|_|
//
// ==================================
// Answer code
// lazy coder variables
var w = canvas.width;
var h = canvas.height;
// ball is simulated 5cm
var pixSize = 0.24; // in millimeters for simulation
// Gravity is 9.8 ms^2 so convert to pixels per frame squared
// Assuming constant 60 frames per second. ()
var gravity = 9800*pixSize/60;
gravity *= 0.101; // because Earth's gravity is stupidly large let's move to Pluto
// ball 5cm
var ballR = (25/pixSize)/2; // radius is 2.5cm for 5cm diamiter ball
var ballX = w/2; // get center of canvas
var ballY = ballR+3; // start at the top
var ballDX = (Math.random()-0.5)*15; // start with random x speed
ballDX += ballDX < 0 ? -5 : 5; // make sure it's not too slow
var ballDY = 0; // star with no downward speed;
var ballLastX = ballX;
var ballLastY = ballY;
//create an image of the Ball
var ball = createColouredBall(ballR,Math.floor(Math.random()*360)); // create an image of ball
// create a background. Image is small as it does not have much detail in it
var background = createGradImage(16,"#5af","#08C");
// time to run for
var runFor = 10*60; // ten secons yimes 60 frames per second
// draws the ball motion blured. This introduces extra complexity
var drawMotionBlur = function(image,px,py,dx,dy,steps){
var i,sx,sy;
sx = dx / steps;
sy = dy / steps;
px -= dx; // move back to start position
py -= dy;
ctx.globalAlpha = 1/(steps*0.8); // set alpha to slightly higher for each step
for(i = 0; i < steps; i+= 1){
ctx.drawImage(image,px+i*sx,py+i*sy);
}
ctx.globalAlpha = 1; // reset alpha
}
// style for text
ctx.fillStyle = "white";
ctx.strokeStyle = "black";
ctx.textAlign = "center";
ctx.lineJoin = "round"; // stop some letters getting ears.
ctx.lineWidth = 3;
ctx.textBaseline = "bottom";
var textCenterX = w/2;
var maxHeight = Infinity;
var lastMaxHeight = ballY;
var slowMotion = false; // slow motion flag
var frameTravel = true; // use frame travel in collision test
var update = function(){
var blurSteps = 10; // motion blur ball render steps
const bSteps = 10;
if(mouseButton === 1){
slowMotion = ! slowMotion;
mouseButton = 0;
}
if(mouseButton === 3){
frameTravel = ! frameTravel;
ballX = w/2; // get center of canvas
ballY = ballR+3; // start at the top
ballDY = 0; // start at 0 y speed
mouseButton = 0;
}
// clear the canvas with background canvas image
ctx.drawImage(background,0,0,w,h);
ballDY += gravity; // accelrate due to grav
// add deltas to ball position
ballX += ballDX;
ballY += ballDY;
// test for collison on left and right walls. Need to
// ajust for motion blur
if (ballX < ballR) {
ballDX = -ballDX; // refect delta x
if (frameTravel) { // if using frame travel time
// blur the outward traveling ball only for the time it has been traveling away
blurSteps = Math.ceil(10 * ((ballX - ballR) / -ballDX));
// get position it should have traveled since
ballX -= (ballX - ballR) * 2;
}else{
ballX = ballR; // move ball to touching wall
blurSteps = 1; // there is no outward motion
}
} else
if (ballX > w - ballR) {
ballDX = -ballDX;
if (frameTravel) { // if using frame travel time
// blur the outward traveling ball only for the time it has been traveling away
blurSteps = Math.ceil(10 * ((ballX - (w - ballR)) / -ballDX));
ballX -= (ballX - (w - ballR)) * 2;
}else{
ballX = w - ballR; // move ball to touching wall
blurSteps = 1; // there is no outward motion
}
}
if (ballY > h - ballR) {
ballDY = -ballDY;
// to show max height
lastMaxHeight = maxHeight;
maxHeight = Infinity;
if (frameTravel) { // if using frame travel time
// blur the outward traveling ball only for the time it has been traveling away
blurSteps = Math.ceil(10 * ((ballY - (h - ballR)) / -ballDY));
ballY -= (ballY - (h - ballR)) * 2;
}else{
ballY = h - ballR; // move ball to touching wall
blurSteps = 1; // there is no outward motion
}
}
// draw the ball motion blured
drawMotionBlur(
ball, // image to draw
ballX - ballR, // offset radius
ballY - ballR,
ballDX * (blurSteps / bSteps), // speed and adjust for bounced
ballDY * (blurSteps / bSteps),
blurSteps // number of blurs
);
// show max height. Yes it is min but everything is upside down.
maxHeight = Math.min(maxHeight,ballY);
lastMaxHeight = Math.min(ballY,lastMaxHeight);
// show max height
ctx.font = "12px arial black";
ctx.beginPath();
ctx.moveTo(0,lastMaxHeight - ballR);
ctx.lineTo(w,lastMaxHeight - ballR);
ctx.stroke();
ctx.fillText("Max height.",40,lastMaxHeight - ballR + 6);
var str = ""; // display status string
if(slowMotion){ // show left click help
str += "10fps."
ctx.fillText("click for 60fps.",textCenterX,43);
}else{
str += "60fps."
ctx.fillText("click for 10fps.",textCenterX,43);
}
if(frameTravel){ // show mode and right click help
str += " Mid frame collision.";
ctx.fillText("Right click for Simple collision",textCenterX,55);
}else{
str += " Simple collision.";
ctx.fillText("Right click for mid frame collision",textCenterX,55);
}
// display help text
ctx.font = "18px arial black";
ctx.strokeText(str,textCenterX,30);
ctx.fillText(str,textCenterX,28);
if(slowMotion){
setTimeout(update,100); // show in slow motion
}else{
requestAnimationFrame(update); // request next frame (1/60) seconds from now
}
// all done
}
update(); // to start the ball rolling
.canC { width:500px; height:500px;}
<canvas class="canC" id="canV" width=500 height=500></canvas>
For a wall running along the X axis at the bottom (Y = 0) of a 650 x 650 field, we would want:
if (player.y <= 20) {
player.y = 20;
}
For a wall running along the Y axis at the left side (X = 0) of a 650 x 650 field, we would want:
if (player.x <= 20) {
player.x = 20;
}
For a wall running along the Y axis at the right side (X = 650) of a 650 x 650 field, we would want:
if (player.x >= 630) {
player.x = 630;
}
For a wall running along the X axis at the top (Y = 650) of a 650 x 650 field, we would want:
if (player.y >= 630) {
player.y = 630;
}
This code is similar to the code I use, if we attach horizontal (h) and vertical (v) velocity attributes to the player object we can multiply them by negative one to get them to bounce off of the wall if the player is going to go beyond the bounds. Or if you want it to stop, set them equal to zero at the wall.
//player.x+player.h gives us the future position of the player
if (player.x+player.h>630||player.x+player.h<0)
{
player.h*=-1;//bounce
//stop player.h=0;
}
if (player.y+player.v>500||player.y+player.v<0)
{
player.v*=-1;
//stop player.v=0;
}
//new player coordinates
player.x+=player.h;
player.y+=player.v;
Hope this helps.

Categories