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.
I try to create a images rotate 360 degree in javascript which is working with left to right perfectly but when I try to move it with bottom to top and top to bottom then it didn't work perfectly I want to create such a demo which show in example
http://www.ajax-zoom.com/examples/example28_clean.php
e(f).mousemove(function(e)
{
if (s == true) dx(e.pageX - this.offsetLeft,e.pageY - this.offsetTop);
else o = e.pageX - this.offsetLeft; f = e.pageY- this.offsetTop;
});
function dx(t,q) {
console.log("t.....x. px.."+t+" -"+ px +"-----q---------y------"+q);
if(f - q > 0.1)
{
f = q;
a="left-top/";
i=43;
r = --r < 1 ? i : r;
e(u).css("background-image", "url(" + a + r + "." + c + ")")
//r = --r < 1 ? i : r;
// e(u).css("background-image", "url(" + a + 73 + "." + c + ")")
}else if (f - q < -0.1) {
f = q;
a="left-top/";
i=43;
r = ++r > i ? 1 : r;
e(u).css("background-image", "url(" + a + r + "." + c + ")")
}
if (o - t > 0.1) {
o = t;
r = --r < 1 ? i : r;
e(u).css("background-image", "url(" + a + r + "." + c + ")")
} else if (o - t < -0.1) {
o = t;
r = ++r > i ? 1 : r;
e(u).css("background-image", "url(" + a + r + "." + c + ")")
}
}
Where : a is path of images folder, r is number of images(1,2,3,4....) and c is .png file
But it is not working perfectly so can Anyone help me...
I think u r pointing out the glitchy movement... U just have to add more images with more perspective
This is one way of doing it by creating a function that converts a view into a Image url. The view has the raw viewing angles and knows nothing about the image URL format or limits. The function createImageURL converts the view to the image URL and applies limits to the view if needed.
An animation function uses the mouse movement to update the view which then calls the URL function to get the current URL. I leave it to you to do the preloading, T
So first Create the vars to hold the current view
const view = {
rotUp : 0,
rotLeftRigh : 0,
speedX : 0.1, // converts from pixels to deg. can reverse with neg val
speedY : 0.1, // converts from pixels to deg
};
Create a function that will take the deg rotate (left right) and the deg rotate up (down) and convert it to the correct image URL.
// returns the url for the image to fit view
function createImageURL(view){
var rotate = view.rotLeftRight;
var rotateUp = view.rotUp;
const rSteps = 24; // number of rotate images
const rStepStringWidth = 3; // width of rotate image index
const upStep = 5; // deg step of rotate up
const maxUp = 90; // max up angle
const minUp = 0; // min up angle
const rotateUpToken = "#UP#"; // token to replace in URL for rotate up
const rotateToken = "#ROT#"; // token to replace in URL for rotate
// URL has token (above two lines) that will be replaced by this function
const url = "http://www.ajax-zoom.com/pic/zoomthumb/N/i/Nike_Air_#UP#_#ROT#_720x480.jpg";
// make rotate fit 0-360 range
rotate = ((rotate % 360) + 360) % 360);
rotate /= 360; // normalize
rotate *= rSteps; // adjust for number of rotation images.
rotate = Math.floor(rotate); // round off value
rotate += 1; // adjust for start index
rotate = "" + rotate; // convert to string
// pad with leading zeros
while(rotate.length < rStepStringWidth) {rotate = "0" + rotate }
// set min max of rotate up;
rotateUp = rotateUp < upMin ? upMin : rotateUp > upMax ? upMax : rotateUp;
view.rotUp = rotateUp; // need to set the view or the movement will
// get stuck at top or bottom
// move rotate up to the nearest valid value
rotateUp = Math.round(rotateUp / upStep) * upStep;
// set min max of rotate again as the rounding may bring it outside
// the min max range;
rotateUp = rotateUp < upMin ? upMin : rotateUp > upMax ? upMax : rotateUp;
url = url.replace(rotateUpToken,rotateUP);
url = url.replace(rotateToken,rotate);
return url;
}
Then in the mouse event you capture the movement of the mouse.
const mouse = {x : 0, y : 0, dx : 0, dy : 0, button : false}
function mouseEvents(e){
mouse.x = e.pageX;
mouse.y = e.pageY;
// as we dont process the mouse events here the movements must be cumulative
mouse.dx += e.movementX;
mouse.dY += e.movementY;
mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
}
And then finally the animation function.
function update(){
// if there is movement
if(mouse.dx !== 0 || mouse.dy !== 0){
view.rotUp += mouse.dy * view.speedY;
view.rotLeftRight += mouse.dx * view.speedX;
mouse.dx = mouse.dy = 0;
// get the URL
const url = createImageURL(view);
// use that to load or find the image and then display
// it if loaded.
}
requestAnimationFrame(update);
}
requestAnimationFrame(update);
he createImageURL could also be used to create a referance to an image in an object.
const URLPart = "http://www.ajax-zoom.com/pic/zoomthumb/N/i/Nike_Air_"
const allImages = {
I_90_001 : (()=>{const i=new Image; i.src=URLPart+"_90_001_720x480.jpg"; return i;})(),
I_90_002 : (()=>{const i=new Image; i.src=URLPart+"_90_002_720x480.jpg"; return i;})(),
I_90_003 : (()=>{const i=new Image; i.src=URLPart+"_90_003_720x480.jpg"; return i;})(),
... and so on Or better yet automate it.
And in the createImageURL use the URL to get the property name for allImages
replacing
const url = "http://www.ajax-zoom.com/pic/zoomthumb/N/i/Nike_Air_#UP#_#ROT#_720x480.jpg";
with
const url = "I_#UP#_#ROT#";
then you can get the image
const currentImage = allImages[createImageURL(view)];
if(currentImage.complete){ // if loaded then
ctx.drawImage(currentImage,0,0); // draw it
}
I have an Isometric engine that I am building:
http://jsfiddle.net/neuroflux/09h43kz7/1/
(Arrow keys to move).
I am updating the Engine.player.x and Engine.player.y to move the character, but (obviously) the player just "pops" from one tile to another.
I wondered if there was a way to make him "slide" from tile to tile?
Or better still, free movement...
I've been pulling my hair out trying.
Here's the relevant code:
var Engine = {
// canvas variables
canvas: null,
ctx: null,
// map
map: [
[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
[2,1,1,1,1,1,1,1,1,1,1,1,1,1,2],
[2,1,1,0,0,1,1,1,1,0,0,0,1,1,2],
[2,2,1,0,0,0,0,1,0,0,0,0,1,1,2],
[2,2,1,1,1,1,0,0,0,0,1,0,0,1,2],
[2,2,2,2,2,1,0,0,0,1,0,0,0,1,2],
[2,2,1,1,1,1,0,0,0,0,0,0,0,1,2],
[2,1,1,0,1,0,0,0,0,1,1,0,0,1,2],
[2,1,0,0,0,0,0,1,0,0,0,0,0,1,2],
[2,1,0,0,0,0,0,0,0,0,1,0,0,1,2],
[2,1,0,0,0,0,1,0,0,0,0,0,0,1,2],
[2,1,0,1,1,0,0,0,0,1,0,0,0,1,2],
[2,1,0,0,0,0,0,0,0,0,1,0,1,1,2],
[2,1,1,1,1,1,1,1,1,1,1,1,1,1,2],
[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]
],
// player info
player: {
x:1,
y:1
},
// tile size
tileH: 31,
tileW: 63,
// map position
mapX: window.innerWidth/2,
mapY: window.innerHeight/3,
// tile images
tileSources: [
"images/stone.png",
"images/grass.png",
"images/water.png",
"images/ralph.png"
],
// for pre-loading
tileGraphics: [],
tilesLoaded: 0,
// image preloader
loadImages: function() {
for (var i = 0; i < Engine.tileSources.length; i++) {
Engine.tileGraphics[i] = new Image();
Engine.tileGraphics[i].src = Engine.tileSources[i];
Engine.tileGraphics[i].onload = function() {
Engine.tilesLoaded++;
if (Engine.tilesLoaded === Engine.tileSources.length) {
Engine.draw();
}
}
}
},
// update logic
update: function() {
Engine.draw();
},
// draw the scene
draw: function() {
Engine.ctx.clearRect(0, 0, Engine.canvas.width, Engine.canvas.height);
var drawTile;
for (var i = 0; i < Engine.map.length; i++) {
for (var j = 0; j < Engine.map[i].length; j++) {
drawTile = Engine.map[i][j];
Engine.ctx.drawImage(Engine.tileGraphics[drawTile], (i - j) * Engine.tileH + Engine.mapX, (i + j) * Engine.tileH / 2 + Engine.mapY);
if (Engine.player.x === i && Engine.player.y === j) {
Engine.ctx.drawImage(Engine.tileGraphics[3], (i - j) * Engine.tileH + Engine.mapX, (i + j) * Engine.tileH / 2 + Engine.mapY - Engine.tileH + 10);
}
}
}
Engine.gameLoop();
},
// game loop
gameLoop: function() {
Engine.gameTimer = setTimeout(function() {
requestAnimFrame(Engine.update, Engine.canvas);
}, 1);
},
// start
init: function() {
Engine.canvas = document.getElementById("main");
Engine.canvas.width = window.innerWidth;
Engine.canvas.height = window.innerHeight;
Engine.ctx = Engine.canvas.getContext("2d");
document.addEventListener("keyup", function(e) {
//console.log(e.keyCode);
switch(e.keyCode) {
case 38:
if (Engine.map[Engine.player.x-1][Engine.player.y] !== 2) {
Engine.player.x--;
}
break;
case 40:
if (Engine.map[Engine.player.x+1][Engine.player.y] !== 2) {
Engine.player.x++;
}
break;
case 39:
if (Engine.map[Engine.player.x][Engine.player.y-1] !== 2) {
Engine.player.y--;
}
break;
case 37:
if (Engine.map[Engine.player.x][Engine.player.y+1] !== 2) {
Engine.player.y++;
}
break;
}
});
Engine.loadImages();
}
}
// loaded
window.onload = function() {
Engine.init();
};
// request animation frame
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback, element){
fpsLoop = window.setTimeout(callback, 1000 / 60);
};
}());
Thanks in advance!
You are drawing the character at tile positions. What you want is to just add a second set of coordinates for the character representing its destination. To move smoothly you can set the characters position in fractions of a tile. Eg player.x = 2.5 the character is halfway between tiles 2 and 3.
Also you want to get rid of the messing about in isometric space. Off load the transformation from 2d to isometric to the draw function, rather than doing it by hand each time you draw to the playfield.
Create the draw function
// add to the Engine object.
// img is the image to draw. x and y are the tile locations.
// offsetX and offsetY [optional] are pixel offsets for fine tuning;
drawImageIso:function (img,x,y,offsetX,offsetY){
offsetX = offsetX === undefined ? 0: offsetX; // so you dont have to
offsetY = offsetY === undefined ? 0: offsetY; // add the offset if you
// are not using it;
Engine.ctx.drawImage( // draw the image
img,
(x - y) * Engine.tileH + Engine.mapX + offsetX,
(x + y) * Engine.tileH / 2 + Engine.mapY - Engine.tileH+offsetY
);
},
Change the player object to
player: {
x:1,
y:1,
destX:1, // the destination tile
destY:1,
playerAtDest:true, // true if the player has arrived
},
Add this befor the tile render loops
var p = Engine.player; // because I am lazy and dont like typing.
var dx = p.destX;
var dy = p.destY;
var maxPlayerSpeed = 0.1; // max speed in tiles per frame
var mps = maxPlayerSpeed; // because I am lazy
// check if the player needs to move
if( Math.abs(p.x - dx) > mps || Math.abs(p.y - dy) > mps ){
p.x += Math.max( -mps , Math.min( mps , dx - p.x )); // move to destination clamping speed;
p.y += Math.max( -mps , Math.min( mps , dy - p.y ));
p.playerAtDest = false; // flag the player is on the way
}else{
// player directly over a till and not moving;
p.x = dx; // ensure the player positioned correctly;
p.y = dy;
p.playerAtDest = true; // flag the player has arrived
}
Add the following where you used to draw the player. Use the destination x,y to determine when to draw or use Math.round(Engine.player.x) and y to determine when.
// now draw the player at its current position
Engine.drawImageIso( Engine.tileGraphics[3] , p.x , p.y , 0 , 10);
You will have to change the interface to move player destination rather than x and y. You may also want to delay the move until the player has arrived at the current destination.
That covers the basics.