I have this game I'm working on with a 2 dimensional array with coordinates and a generalized coordinate system (i.e. player x = 0 and y = 0, it's standing in the first item in the array). I'm trying to work out a solution to collision detection and resolving, but I'm having a really hard time.
This is my code so far (detecting collisions but not resolving them correctly and I have just no clue how to fix thayut):
let xOffset = 0;
let yOffset = 0;
let self = this;
let a, b, c, d, e, f, g, h;
// get the 4 colliding tiles from the layout array
function reset() {
a = Math.floor(self.x);
b = Math.ceil(self.x);
c = Math.floor(self.y);
d = Math.ceil(self.y);
e = (currentClassRoom.layout[c] || [])[a];
f = (currentClassRoom.layout[c] || [])[b];
g = (currentClassRoom.layout[d] || [])[a];
h = (currentClassRoom.layout[d] || [])[b];
}
function X() {
// x collisions
// get the distance inside the block from corresponding direction
if (Walkable.indexOf(f) < 0 || Walkable.indexOf(h) < 0) { xOffset += -(self.x - a) }
if (Walkable.indexOf(e) < 0 || Walkable.indexOf(g) < 0) { xOffset += 1 - (self.x - a) }
}
function Y() {
// y collisions
// get the distance inside the block from corresponding direction
if (Walkable.indexOf(e) < 0 || Walkable.indexOf(f) < 0) { yOffset += 1 - (self.y - c) };
if (Walkable.indexOf(g) < 0 || Walkable.indexOf(h) < 0) { yOffset += -(self.y - c) };
}
// run and resolve
reset();
Y();
this.y += yOffset;
X();
this.x += xOffset;
Is there something wrong with my code or is a generalized coordinate system a bad idea in my case? I haven't made anything like this and can't seem to find solutions online (which might be an indicator that the way I'm thinking about this is bad but I just don't know)
Related
I am trying to solve a school assignment in p5 JavaScript. I want something to move over the canvas after one mouseclick. But it only moves a little bit and I have to click several times to get it all the way over. What have I done wrong? Shouldn't the loop make it move all the way? Can post the whole code if needed.
function CanvasPressed()
{
if ( mouseX > 0 && mouseX < 638 && mouseY > 0 && mouseY < 100 )
{
Bird.stop();
Bird.play();
for ( let b = 640; b > 0; b--)
{
x = x - 0.05;
}
}
Alright, so you've got a couple misunderstood things, here:
// purely aesthetic but in javascript functions are usually written as (i think) camelCase
// so: canvasPressed() rather than CanvasPressed(), Class-es start with upper case
function CanvasPressed()
{
// you can check for width & height if you want if ( mouseX > 0 && mouseX < width)
if ( mouseX > 0 && mouseX < 638 && mouseY > 0 && mouseY < height )
{
for ( let b = 640; b > 0; b--) // this, in this case, does the same as for(let i = 0; i < width; i ++)
{
x += 0.05
// 0.05 is very little, only a very small part of a pixel
}
// here it moves 0.05 * 640 (0.05 + 0.05 + 0.05 ... )
}
}
javascript naming conventions thingy if you want
and this is how i would make it move through the canvas:
let mouseWasPressed = false;
let x = 20
function draw() {
background(20);
ellipse(x, height / 2, 40)
if(mouseWasPressed) // don't need {} for 1 line after the if()
x ++; // x = x + 1 shortening in javascript
// }
}
function mousePressed(){
mouseWasPressed = true
}
if you don't want the "animation" you could use your previous method, but change the 0.05 to 1:
for(let i = 0; i <= width; i ++) // you don't have to add parentheses for 1 line
x ++; // x = x + 1 just a shortening in javascript
OR just
x = width // or x += width (x = x + width)
I want to implement a rocket flying through space, which bounces off from incoming meteroids. Currently I have implemented it by comparing the x and y position of both actors and swapping their speeds on collision. The detection of a collision and the speed swapping does work (proved by console.log), however on the screen they only sometimes bounce off.
I tried to make sure that the speed objects of the compared actors do not reference the same JavaScript object (with cSpeedX etc).
The game is built with Pixi JS.
The collision detection function, executed for each actor (all meteroids and the rocket)
export const checkCollision = (current, objects) => {
objects.forEach((o) => {
if (current !== o) {
const dx =
current.x < o.x
? o.x - o.width / 2 - (current.x + current.width / 2)
: current.x - current.width / 2 - (o.x + o.width / 2);
const dy =
current.y < o.y
? o.y - o.height / 2 - (current.y + current.height / 2)
: current.y - current.height / 2 - (o.y + o.height / 2);
if (dx < 0 && dy < 0) {
const cSpeedX = current.speed.x;
const cSpeedY = current.speed.y;
const oSpeedX = o.speed.x;
const oSpeedY = o.speed.y;
current.speed.x = oSpeedX;
current.speed.y = oSpeedY;
o.speed.x = cSpeedX;
o.speed.y = cSpeedY;
}
}
});
The move function implemented both on the rocket and meteroids
this.move = (delta) => {
this.x += this.speed.x * delta;
this.y += this.speed.y * delta;
};
export const checkCollision = (current, objects) => {
objects.forEach((o) => {
if (current !== o) {
You wrote also: The collision detection function, executed for each actor (all meteroids and the rocket)
so i suppose somewhere there is also loop like:
objects.forEach((o) => {
checkCollision(o, objects);
});
This would mean that for every pair of objects the collision is checked twice.
Lets assume that o1 and o2 are some different objects, and that they collide. What will happen then? :
checkCollision(o1, objects); <-- swap speed between o1 and o2
...
checkCollision(o2, objects); <-- swap speed between o2 and o1
So speed will be swapped 2 times between them - in other words: speed of both objects will remain the same.
To investigate if this is indeed the case you can put console.log (or something to print id of object) like this:
if (dx < 0 && dy < 0) {
console.log('swapping speed of of objects:');
console.log(current);
console.log(o);
const cSpeedX = current.speed.x;
Then prepare situation when 2 objects collide and check console logs.
Trying to write a simple web app to solve the following common calculus problem in JavaScript.
Suppose you wanted to make an open-topped box out of a flat piece of cardboard that is L long by W wide by cutting the same size
square (h × h) out of each corner and then folding the flaps to form the box,
as illustrated below:
You want to find out how big to make the cut-out squares in order to maximize the volume of the box.
Ideally I want to avoid using any calculus library to solve this.
My initial naive solution:
// V = l * w * h
function getBoxVolume(l, w, h) {
return (l - 2*h)*(w - 2*h)*h;
}
function findMaxVol(l, w) {
const STEP_SIZE = 0.0001;
let ideal_h = 0;
let max_vol = 0;
for (h = 0; h <= Math.min(l, w) / 2; h = h + STEP_SIZE) {
const newVol = getBoxVolume(l, w, h);
if (max_vol <= newVol) {
ideal_h = h;
max_vol = newVol;
} else {
break;
}
}
return {
ideal_h,
max_vol
}
}
const WIDTH_1 = 20;
const WIDTH_2 = 30;
console.log(findMaxVol(WIDTH_1, WIDTH_2))
// {
// ideal_h: 3.9237000000038558,
// max_vol: 1056.3058953402121
// }
The problem with this naive solution is that it only gives an estimate because you have to provide STEP_SIZE and it heavily limits the size of the problem this can solve.
You have an objective function: getBoxVolume(). Your goal is to maximize the value of this function.
Currently, you're maximizing it using something equivalent to sampling: you're checking every STEP_SIZE, to see whether you get a better result. You've identified the main problem: there's no guarantee the edge of the STEP_SIZE interval falls anywhere near the max value.
Observe something about your objective function: it's convex. I.e., it starts by going up (when h = 0, volume is zero, then it grows as h does), it reaches a maximum, then it goes down, eventually reaching zero (when h = min(l,w)/2).
This means that there's guaranteed to be one maximum value, and you just need to find it. This makes this problem a great case for binary search, because given the nature of the function, you can sample two points on the function and know which direction the maximum lies relative to those two points. You can use this, with three points at a time (left, right, middle), to figure out whether the max is between left and middle, or middle and right. Once these values get close enough together (they're within some fixed amount e of each other), you can return the value of the function there. You can even prove that the value you return is within some value e' of the maximum possible value.
Here's pseudocode:
max(double lowerEnd, upperEnd) {
double midPoint = (upperEnd + lowerEnd) / 2
double midValue = getBoxVolume(l, w, midpoint)
double slope = (getBoxVolume(l, w, midpoint + epsilon) - midValue) / epsilon
if (Math.abs(slope) < epsilon2) { // or, if you choose, if (upperEnd - lowerEnd < epsilon3)
return midpoint
}
if (slope < 0) { // we're on the downslope
return max(lowerEnd, midPoint)
}
else { // we're on the up-slope
return max(midpoint, upperEnd)
}
}
After realising that the derivative of the volume function is a second degree polynomial you can apply a quadratic formula to solve for x.
Using calculus, the vertex point, being a maximum or minimum of the function, can be obtained by finding the roots of the derivative
// V = l * w * h
function getBoxVolume(l, w, h) {
return (l - 2*h)*(w - 2*h)*h;
}
// ax^2 + bx + c = 0
function solveQuad(a, b, c) {
var x1 = (-1 * b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
var x2 = (-1 * b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
return { x1, x2 };
}
function findMaxVol(l, w) {
// V'(h) = 12h^2-4(l+w)h+l*w - second degree polynomial
// solve to get the critical numbers
const result = solveQuad(12, -4*(l + w), l*w)
const vol1 = getBoxVolume(l, w, result.x1);
const vol2 = getBoxVolume(l, w, result.x2);
let ideal_h = 0;
let max_vol = 0;
// check for max
if (vol1 > vol2) {
ideal_h = result.x1;
max_vol = vol1;
} else {
ideal_h = result.x2;
max_vol = vol2;
}
return {
ideal_h,
max_vol
}
}
const WIDTH_1 = 20;
const WIDTH_2 = 30;
console.log(findMaxVol(WIDTH_1, WIDTH_2))
// {
// ideal_h: 3.9237478148923493,
// max_vol: 1056.30589546119
// }
I'm building a website which uses jQuery to allow users to add widgets to a page, drag them around and resize them (the page is fixed width and infinite height.) The issue that I'm having is that when adding a new widget to the page I have to find a free space for it (the widgets cannot overlap and I'd like to favour spaces at the top of the page.)
I've been looking at various packing algorithms and none of them seem to be suitable. The reason why is that they are designed for packing all of the objects in to the container, this means that all of the previous rectangles are laid out in a uniform way. They often line up an edge of the rectangle so that they form rows/columns, this simplifies working out what will fit where in the next row/column. When the user can move/resize widgets at will these algorithms don't work well.
I thought that I had a partial solution but after writing some pseudo code in here I’ve realized that it won’t work. A brute force based approach would work, but I'd prefer something more efficient if possible. Can anyone suggest a suitable algorithm? Is it a packing algorithm that I'm looking for or would something else work better?
Thanks
Ok, I've worked out a solution. I didn't like the idea of a brute force based approach because I thought it would be inefficient, what I realized though is if you can look at which existing widgets are in the way of placing the widget then you can skip large portions of the grid.
Here is an example: (the widget being placed is 20x20 and page width is 100px in this example.)
This diagram is 0.1 scale and got messed up so I've had to add an extra column
*123456789A*
1+---+ +--+1
2| | | |2
3| | +--+3
4| | 4
5+---+ 5
*123456789A*
We attempt to place a widget at 0x0 but it doesn't fit because there is a 50x50 widget at that coordinate.
So we then advance the current x coordinate being scanned to 51 and check again.
We then find a 40x30 widget at 0x61.
So we then advance the x coordinate to 90 but this doesn't leave enough room for the widget being placed so we increment the y coordinate and reset x back to 0.
We know from the previous attempts that the widgets on the previous line are at least 30px high so we increase the y coordinate to 31.
We encounter the same 50x50 widget at 0x31.
So we increase x to 51 and find that we can place a widget at 51x31
Here is the javascript:
function findSpace(width, height) {
var $ul = $('.snap-layout>ul');
var widthOfContainer = $ul.width();
var heightOfContainer = $ul.height();
var $lis = $ul.children('.setup-widget'); // The li is on the page and we dont want it to collide with itself
for (var y = 0; y < heightOfContainer - height + 1; y++) {
var heightOfShortestInRow = 1;
for (var x = 0; x < widthOfContainer - width + 1; x++) {
console.log(x + '/' + y);
var pos = { 'left': x, 'top': y };
var $collider = $(isOverlapping($lis, pos, width, height));
if ($collider.length == 0) {
// Found a space
return pos;
}
var colliderPos = $collider.position();
// We have collided with something, there is no point testing the points within this widget so lets skip them
var newX = colliderPos.left + $collider.width() - 1; // -1 to account for the ++ in the for loop
x = newX > x ? newX : x; // Make sure that we are not some how going backwards and looping forever
var colliderBottom = colliderPos.top + $collider.height();
if (heightOfShortestInRow == 1 || colliderBottom - y < heightOfShortestInRow) {
heightOfShortestInRow = colliderBottom - y; // This isn't actually the height its just the distance from y to the bottom of the widget, y is normally at the top of the widget tho
}
}
y += heightOfShortestInRow - 1;
}
//TODO: Add the widget to the bottom
}
Here is the longer and more less elegant version that also adjusts the height of the container (I've just hacked it together for now but will clean it up later and edit)
function findSpace(width, height,
yStart, avoidIds // These are used if the function calls itself - see bellow
) {
var $ul = $('.snap-layout>ul');
var widthOfContainer = $ul.width();
var heightOfContainer = $ul.height();
var $lis = $ul.children('.setup-widget'); // The li is on the page and we dont want it to collide with itself
var bottomOfShortestInRow;
var idOfShortestInRow;
for (var y = yStart ? yStart : 0; y <= heightOfContainer - height + 1; y++) {
var heightOfShortestInRow = 1;
for (var x = 0; x <= widthOfContainer - width + 1; x++) {
console.log(x + '/' + y);
var pos = { 'left': x, 'top': y };
var $collider = $(isOverlapping($lis, pos, width, height));
if ($collider.length == 0) {
// Found a space
return pos;
}
var colliderPos = $collider.position();
// We have collided with something, there is no point testing the points within this widget so lets skip them
var newX = colliderPos.left + $collider.width() - 1; // -1 to account for the ++ in the for loop
x = newX > x ? newX : x; // Make sure that we are not some how going backwards and looping forever
colliderBottom = colliderPos.top + $collider.height();
if (heightOfShortestInRow == 1 || colliderBottom - y < heightOfShortestInRow) {
heightOfShortestInRow = colliderBottom - y; // This isn't actually the height its just the distance from y to the bottom of the widget, y is normally at the top of the widget tho
var widgetId = $collider.attr('data-widget-id');
if (!avoidIds || !$.inArray(widgetId, avoidIds)) { // If this is true then we are calling ourselves and we used this as the shortest widget before and it didnt work
bottomOfShortestInRow = colliderBottom;
idOfShortestInRow = widgetId;
}
}
}
y += heightOfShortestInRow - 1;
}
if (!yStart) {
// No space was found so create some
var idsToAvoid = [];
for (var attempts = 0; attempts < widthOfContainer; attempts++) { // As a worse case scenario we have lots of 1px wide colliders
idsToAvoid.push(idOfShortestInRow);
heightOfContainer = $ul.height();
var maxAvailableRoom = heightOfContainer - bottomOfShortestInRow;
var extraHeightRequired = height - maxAvailableRoom;
if (extraHeightRequired < 0) { extraHeightRequired = 0;}
$ul.height(heightOfContainer + extraHeightRequired);
var result = findSpace(width, height, bottomOfShortestInRow, idsToAvoid);
if (result.top) {
// Found a space
return result;
}
// Got a different collider so lets try that next time
bottomOfShortestInRow = result.bottom;
idOfShortestInRow = result.id;
if (!bottomOfShortestInRow) {
// If this is undefined then its broken (because the widgets are bigger then their contianer which is hardcoded atm and resets on f5)
break;
}
}
debugger;
// Something has gone wrong so we just stick it on the bottom left
$ul.height($ul.height() + height);
return { 'left': 0, 'top': $ul.height() - height };
} else {
// The function is calling itself and we shouldnt recurse any further, just return the data required to continue searching
return { 'bottom': bottomOfShortestInRow, 'id': idOfShortestInRow };
}
}
function isOverlapping($obsticles, tAxis, width, height) {
var t_x, t_y;
if (typeof (width) == 'undefined') {
// Existing element passed in
var $target = $(tAxis);
tAxis = $target.position();
t_x = [tAxis.left, tAxis.left + $target.outerWidth()];
t_y = [tAxis.top, tAxis.top + $target.outerHeight()];
} else {
// Coordinates and dimensions passed in
t_x = [tAxis.left, tAxis.left + width];
t_y = [tAxis.top, tAxis.top + height];
}
var overlap = false;
$obsticles.each(function () {
var $this = $(this);
var thisPos = $this.position();
var i_x = [thisPos.left, thisPos.left + $this.outerWidth()]
var i_y = [thisPos.top, thisPos.top + $this.outerHeight()];
if (t_x[0] < i_x[1] && t_x[1] > i_x[0] &&
t_y[0] < i_y[1] && t_y[1] > i_y[0]) {
overlap = this;
return false;
}
});
return overlap;
}
I'm doing a BattleShip game in javascript with iio engine.
I'm trying to play against a computer so I have to put a random position for the ships (I hope you know the game :) ).
I have 5 ships that have to be placed in a grid (10x10). The problem is that the function is pretty slow, and sometimes the page don't get load at all.
I want to know if there are some emprovement for the speed of these function, I'm a little bit newbie :D
function posShips(size){
// var size -> size of the ship
var isOk = false; // flag var to check if the ship is in a right position
var isOk2 = true; // flag var, become false if the cell is already fill with another ship
var i;
var j;
var side; // horizontal or vertical
while(!isOk){
i = iio.getRandomInt(1,11);
j = iio.getRandomInt(1,11);
side = iio.getRandomInt(0,2);
if((side ? j : i)+size-1 < 11){ // Not out of the array
for (var k = 0; k < size; k++) { // Size of the ship
if(side){
if(gridHit[i][j+k].stat == "empty"){ //If is empty put the ship
gridHit[i][j+k].stat = "ship";
gridHit[i][j+k].setFillStyle("red")
}else{ // If not empty
isOk2 = false; //Position is not good, do all the thing again.
for (var a = 0; a < size; a++) { // Reset cell
gridHit[i][j+a].stat = "empty";
}
k = 10;
}
}else{
if(gridHit[i+k][j].stat == "empty"){ //If is empty put the ship
gridHit[i+k][j].stat = "ship";
gridHit[i+k][j].setFillStyle("red")
}else{ // If not empty
isOk2 = false; //Position is not good, do all the thing again.
for (var a = 0; a < size; a++) { // Reset cell
gridHit[i+a][j].stat = "empty";
}
k = 10;
}
}
};
if(isOk2)
isOk = true;
}
}
}
Don't pick ship positions that will fall outside the grid. Pick the direction first, and then limit the x and y initial positions based on size. e.g. if the size is 3, there's no point going above 7 for the initial value of the varying coordinate.
Don't change the array while you're searching. Do the search first, and only afterwards update the array. This avoids any "cleanup" operation.
Wherever possible, eliminate repeated deep object references. If accessing grid[y][x] repeatedly for differing x, take a reference to grid[y] first, and then use that for the subsequent accesses.
Break out of loops early, there's no point continuing to test a position if a previous one already failed.
Place your big ships first - it's easier to fit small ships into the gaps left between the big ones.
See http://jsfiddle.net/alnitak/Rp9Ke/ for my implementation, with the equivalent of your function being this:
this.place = function(size) {
// faster array access
var g = this.grid;
// initial direction, and vector
var dir = rand(2); // 0 - y, 1 - x
var dx = dir ? 1 : 0;
var dy = dir ? 0 : 1; // or 1 - dx
LOOP: while (true) {
// initial position
var x = dir ? rand(10 - size) : rand(10);
var y = dir ? rand(10) : rand(10 - size);
// test points
var n = size, tx = x, ty = y;
while (n--) {
if (g[ty][tx]) continue LOOP;
tx += dx;
ty += dy;
}
// fill points
n = size;
while (n--) {
g[y][x] = size;
x += dx;
y += dy;
}
break;
}
};