vendredi 17 juin 2016

ActionScript: Intersection multiple objects while not intersecting any?

I have been working on a hit detection algorithm for a while, where I have a series of squares which are in an array (blocks), and through a loop, the array is gone through and it is checked if an item (bus) is intersecting it.

The original code goes as follows:

// Gets important variables from controller class
var blocks:Array = main.blocks;
var map:Map = main.game.gameMap;
var game:GameMapScreen = main.game;
var busSpeed:uint = 5;

// Centers the 'map' around the 'bus'
game.x = (bus.x) * -1  + stage.stageWidth / 2;
game.y = (bus.y) * -1 + stage.stageHeight / 2;
map.setChildIndex(bus, map.numChildren - 1);

// Creates the new x and y values for where the bus will move
var angle:Number = (bus.rotation / 360) * (Math.PI * 2);
var dx:Number = Math.cos(angle);
var dy:Number = Math.sin(angle);
var newX:Number = dx * busSpeed;
var newY:Number = dy * busSpeed;

// Gets a clone of rectangle around bus, moves it to new x and y
busRect.x += newX;
busRect.y += newY;

And then it goes through the blocks array and tests the bus rectangle again each block's rectangle

var hitting:Boolean = false;
for(var i:uint = 0; i < blocks.length; i++)
{
   if(busRect.intersections(blocks[i].getRect(map))
   {
      hitting = true;
      break;
   }
}

And then it checks to see if hitting, then moves if not

if(hitting)
{
   bus.x = newX;
   bus.y = newY;
}

The problem I discovered was that when the bus is not intersecting a block, it appears to be "intersecting" two blocks.

The blocks are arranged in a grid-like fashion, with spaces in between where it should not be intersecting... but it appears to be intersection two, and only one when actually inserting a block.

After checking many times and consulting with others, we cannot figure out the problem. Why is it that when we arrange the blocks in a grid like fashion, stick then in an array, and checks if it is hitting something, it intersection 2 blocks if not actually intersecting, and intersection 1 if it is...

Any ideas?

Aucun commentaire:

Enregistrer un commentaire