How to check for specific collisions in cocos2d-x v3.1? C++ - c++

I'm attempting to check for specific collisions between sprites with Physics bodies. The problem is that I don't know how to assign either a tag to each node physics body or set the collision bitmask properly for each sprite. I am successfully checking for collisions but it's only a true or false for all objects.
I'm following a guide in the cocos2d-x documentation that I've linked below. In it, it explains how to set masking bits and masking categories.
Collision filtering allows you to prevent collision between shapes. Cocos2d-x >supports collision filtering using category and groups bitmasks.
Cocos2d-x supports 32 collision categories. For each shape you can specify which category it belongs to. You also specify what other categories this shape can collide with. This is done with masking bits
The problem is that when I set:
sprite1->getPhysicsBody()->setCategoryBitmask(0x02); // 0010
sprite1->getPhysicsBody()->setCollisionBitmask(0x01); // 0001
There isn't collision detection for those sprites. But when I set:
invaderPhysicsBody->setContactTestBitmask(true);
There is a collision detection.
Does anybody know how to successfully set the collision bitmask or category bitmask?
Objects with possible collisions:
Vector of sprites for invaders.
Vector of player missiles
Vector of invader missiles
Sprite for player
Four sprites for shields
This is my onContactBegin function that will remove the Node once they collide. This is where I need to test which objects collided.
bool Gameplay::onContactBegin(PhysicsContact &contact) {
std::cout << "onContactBegin -------> " << std::endl;
player_score += 10;
auto nodeA = contact.getShapeA()->getBody()->getNode();
auto nodeB = contact.getShapeB()->getBody()->getNode();
std::cout << contact.getShapeA()->getTag() << std::endl;
if ((contact.getShapeA()->getCategoryBitmask() & contact.getShapeB()->getCollisionBitmask()) == 0
|| (contact.getShapeB()->getCategoryBitmask() & contact.getShapeA()->getCollisionBitmask()) == 0)
{
std::cout << "Overlap!" << std::endl;
}
nodeA->removeFromParent();
nodeB->removeFromParent();
return true;
}
Here is my collision listener:
// Enable collision listener.
auto contactListener = EventListenerPhysicsContact::create();
contactListener->onContactBegin = CC_CALLBACK_1(Gameplay::onContactBegin, this);
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this);
This is how I currently create and set the Physics bodies for my sprites:
int spacing = 0;
// Four Player Shields
for (int i = 0; i < 4; i++) {
auto shield = Sprite::create("player_shield.png");
auto shield_x = shield->getContentSize();
auto shield_y = shield->getContentSize();
auto shieldPhysicsBody = PhysicsBody::createBox(Size(shield_x.width,shield_y.height), PHYSICSBODY_MATERIAL_DEFAULT);
shieldPhysicsBody->setContactTestBitmask(true);
shieldPhysicsBody->setDynamic(true);
shieldPhysicsBody->setTag(0);
shield->setPosition(Vec2(200 + spacing, 150));
shield->addComponent(shieldPhysicsBody);
this->addChild(shield);
spacing += 200;
}
Here is the guide I've been following.

There is a big mistake in your code. setContactTestBitmask accept a int rather than bool. When you call shieldPhysicsBody->setContactTestBitmask(true), it's actually shieldPhysicsBody->setContactTestBitmask(0x0000001). And 0x000001 & 0x000010 = 0, so no contact event will be raised. The & result of spriteA's categoryBitmask and spriteB's ContactTestBitmask determines whether a contact event will be raised. BTW, generally speaking, you don't need check contaction manually, ie:
if ((contact.getShapeA()->getCategoryBitmask() & contact.getShapeB()->getCollisionBitmask()) == 0
|| (contact.getShapeB()->getCategoryBitmask() & contact.getShapeA()->getCollisionBitmask()) == 0)
{
std::cout << "Overlap!" << std::endl;
}

Related

Problem using collision detection to increment the game score in SFML 2.4

I am making a flappy bird game just to get an idea of how to make games using SFML 2.4 and C++. I have a scoring system which is supposed to increment the score by 1 everytime the bird sprite intersects with an invisible pipe. However, instead of incrementing the score by 1 the score comes to around 57 and 60. Any ideas to get this working is really appreciated.
int main()
{
int score = 0;
float PipeInvisi = 200.0;
while(window.isOpen())
{
if (state == State::PLAYING)
{
// Setup the Invisible Pipe for Movement
if (!PipeInvisbleActive)
{
// How fast is the Pipe
spriteInvisi.setPosition(905, 0);
PipeInvisbleActive = true;
}
else
{
spriteInvisi.setPosition(spriteInvisi.getPosition().x - (PipeInvisi * dt.asSeconds()), spriteInvisi.getPosition().y);
// Has the pipe reached the right hand edge of the screen?
if (spriteInvisi.getPosition().x < -165)
{
// Set it up ready to be a whole new cloud next frame
PipeInvisbleActive = false;
}
}
// Has the Bird hit the invisible pipe
Rect<float> Birdie = spriteBird.getGlobalBounds();
Rect<float> Paipu5 = spriteInvisi.getGlobalBounds();
if (Birdie.intersects(Paipu5))
{
// Update the score text
score++;
std::stringstream ss;
ss << "Score = " << score;
scoreText.setString(ss.str());
clock.restart();
}
}
}
}
Assuming that your problem stems from constant intersection, you could introduce a simple flag that marks the intersection.
bool isBirdIntersectingPipe = false;
Then in your game loop you could detect the beginning of intersection like so.
if (birdRect.intersects(pipeRect)) // Intersection this frame.
{
if (!isBirdIntersectingPipe) // No intersection last frame, so this is the beginning.
{
++score;
isBirdIntersectingPipe = true;
}
// Still intersecting, so do nothing.
}
else // No intersection this frame.
{
isBirdIntersectingPipe = false;
}
Ideally you would have a dedicated collision or even physics system that would track all objects on the scene, but in this case a simple solution like this should suffice.

QT collision detection between 2 QGraphicsPixmapItems

Link to project
The interesting parts should be in gameengine.cpp's "launchSplash" -function and splashanimation.cpp
The game creates the bubbles randomly in the acceptable are. The player's job is to shoot the bubbles with water drops. The water drops are launched from the middle bottom part of the game screen. The grids are only used for debugging, and will later on be gone, but it makes visualizing the areas easier.
The bubbles are destroyed by shooting the water drop at them, but the water drop disappears when it hits a bubble or the upper boundary of the game. The water drop shoots to the direction of a mouse click.
I'm trying to create a collision detection for a basic bubble shooter game, but I'm not sure how I can detect the collision in a neat way.
The game board looks something like this game board, the water drops are shot from the middle bottom part of the screen to the direction of the cursor.
Eventually I'll have the water drop ricochet from the walls, but at the moment I'm contempt with figuring out how to detect collisions in the first place.
The game board is 500x600 units (width x height), so the point the water drop is shot at is (250, 600).
When the water drop is shot, I use
void GameEngine::launchSplash(int clickX, int clickY){
// <my long method of calculating the coordinates for the water drop's path>
graphicalGameBoard_.animateSplash(graphicalGameBoard_.width()/2, graphicalGameBoard_.height(), xDestination, yDestination);
}
where xDestination and yDestionation are the place the water drop will end up if it travels unhindered. The water drop will either end up at x=0 / x=500 and/or y=0/y=600, but I don't think that's relevant.
The bubbles are added to the game board with
board_.clear();
for(int y = 0; y < HEIGHT; ++y)
{
std::vector< std::shared_ptr<Bubble> > row;
for(int x = 0; x < WIDTH; ++x)
{
std::shared_ptr<Bubble> newBubble = nullptr;
// There will be bubbles only in the top 3/4 of the board only in the middle
// (i.e. not in the first two and last two columns).
if (y < HEIGHT*3/4 && x > 1 && x < WIDTH-2)
{
// Generate random numbers using the enumearation type defined in
// file bubble.hh. The value COLOR_COUNT is used to represent no bubble.
std::uniform_int_distribution<int> distribution(RED,COLOR_COUNT);
// If you want no empty squares, change the initialization to:
// std::uniform_int_distribution<int> distribution(RED,BLUE);
Color color = static_cast<Color>(distribution(randomEngine_));
if(color != COLOR_COUNT) {
newBubble = std::make_shared<Bubble>(x, y, color);
}
}
row.push_back(newBubble);
}
board_.push_back(row);
}
in the gameengine.cpp which draws the board and the water drop being shot at the bubbles.
The water drops are drawn using
SplashAnimation::SplashAnimation(GameBoard* scene, QPointF startPoint, QPointF endPoint):
QVariantAnimation(0),
scene_(scene),
item_()
{
scene_->addItem(&item_);
// The animation runs for the given duration and moves the splash
// smoothly from startpoint to endpoint.
setDuration(2000);
setKeyValueAt(0, QPointF(startPoint));
setKeyValueAt(1, QPointF(endPoint));
}
I figured there are two ways to do this: either the inbuilt QT Collision detection or doing a separate calculation. I was not able to work with QT Collision and my attempts at detecting the collision manually did not really work out too well.
I already have a function for detecting bubble objects at certain cells, but it's in column/row instead of raw coordinates (500x600).
std::shared_ptr<Bubble> GameEngine::bubbleAt(int x, int y) const
{
if (0 <= x and x < WIDTH and 0 <= y and y < HEIGHT){
return board_.at(y).at(x);
}
else{
return nullptr;
}
}
Edit: Currently I'm trying to work on something like this, but I'm afraid it's going to be a bit heavy for the game since it iterates so much (or not?):
for (int i = 0; i<600;++i)
{
xfract = (xDestination+250.0)/600.0;
yfract = (600.0-yDestination)/600.0;
xStep = xfract*i;
yStep = yfract*i;
if (xStep >= 50){
thisX = xStep/50-5;
}else{
thisX=5;
}
if (yStep >= 50){
thisY = 11-yStep/50 + 1;
}else{
thisY = 11;
}
thisX = abs(thisX);
if (bubbleAt(thisX, thisY)!=nullptr){
endX = xfract*i;
endY = yfract*i;
i = 600;
std::cout << "collision at x: "<<thisX<< " y: "<<thisY<<std::endl;
std::cout << "collision at x: "<<xStep<< " y: "<<yStep<<std::endl;
std::cout << graphicalGameBoard_.width() << " " << graphicalGameBoard_.height()<<std::endl;
removeBubble(thisX, thisY);
graphicalGameBoard_.removeBubble(thisX, thisY);
endY = 600-endY;
}
}
graphicalGameBoard_.animateSplash(graphicalGameBoard_.width()/2, graphicalGameBoard_.height(), endX, endY);
I'm trying to split the steps into small fractions and check if the current step has a bubble in it until the water drop reaches the end or finds a bubble.
This works on my only one of my sides in terms of calculating, but the animation is off the mark and right side (x>250) collision detection doesn't work at all for some reason (it hits seemingly random bubbles at impossible locations on the right side).
Edit^2: Here are things I've tried in order to work with the actual collision detection of QT:
Within splashanimation.cpp, where the water drop is drawn using
SplashAnimation::SplashAnimation(GameBoard* scene, QPointF startPoint, QPointF endPoint):
QVariantAnimation(0),
scene_(scene),
item_()
{
scene_->addItem(&item_);
// The animation runs for the given duration and moves the splash
// smoothly from startpoint to endpoint.
setDuration(2000);
setKeyValueAt(0, QPointF(startPoint));
setKeyValueAt(1, QPointF(endPoint));
}
SplashAnimation::~SplashAnimation()
{
scene_->removeItem(&item_);
}
void SplashAnimation::updateCurrentValue(QVariant const& value)
{
item_.setPos(value.toPointF());
}
where scene is QGraphicsScene, and the parent of this contains the bubbles.
I've tried this on both the gameboard.cpp (which is parent for bubbles and the animation) and splash.cpp (which animates the water drop), but both give me the same compilation errors.
QGraphicsItem::QGraphicsItem();
gives
error: cannot call constructor ?QGraphicsItem::QGraphicsItem? directly [-fpermissive]
QGraphicsItem::QGraphicsItem();
^
QList<QGraphicsItem *> list = collidingItems() ;
gives error: ?collidingItems? was not declared in this scope
QList<QGraphicsItem *> list = collidingItems() ;
^
QList<QGraphicsItem *> list = QGraphicsItem::collidingItems() ;
gives error: cannot call member function ?QList<QGraphicsItem*> QGraphicsItem::collidingItems(Qt::ItemSelectionMode) const? without object
QList<QGraphicsItem *> list = QGraphicsItem::collidingItems() ;
^
I also tried adding arguments, but nothing I had the mind to try worked any better.
In this answer I am going to give you some recommendations that you use to implement the solution:
Avoid using the following instruction, use the signals that is one of the most powerful elements of Qt and that the event loop does the work.
while (animations_.state() == QAbstractAnimation::Running)
{
QCoreApplication::processEvents(QEventLoop::AllEvents);
}
QGraphicsScene works with coordinates that support the floating point, so the coordinates of the scene are handled with QPointF.
Using the above, if you are going to send point information use QPointF instead of int, int in the signals.
Use the methods that Qt provides, for example the following:
if (0 <= clickPosition.x() and clickPosition.x() <= GRID_SIDE*WIDTH and
0 <= clickPosition.y() and clickPosition.y() <= GRID_SIDE*HEIGHT)
It can be reduced to the following:
if(sceneRect().contains(event->scenePos()))
The advantage of that implementation is that it is more readable
I do not understand why you can not implement collidingItems, maybe it's the configuration of your .pro,
Use the following to add the gui module, core and widgets
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
Also to implement the animation use my previous answer
The complete and functional code can be found at the following link.

in C++, SFML, How do I draw an animation from another class within a different class?

I am making a street fighter type game for my University project using c++ and SFML, I am new to this so I don't really know what I'm doing.
I wanted to have a teleport button that lets the player teleport 700 pixels away from their current position and have an animation (smoke effect) play when they move.
I have made a separate class for this animation which has an update function that plays each frame. But I don't know how to use the animation from the "Teleport" class in the "Player" class.
Any help would be greatly appreciated...
Code: (the 'isSliding' is a confusing variable name but it's meant to mean teleporting)
if ((input->isKeyDown(sf::Keyboard::D)) && (!isSliding) && (hDir != 0)) //slide: if slide is pressed AND cooldown is finished.
{
cout << "\nSlide pressed!";
cout << "\nElapsed slide time: " + to_string(slideElapsedTime);
if (playerStamina >= slideCost)
{
//isAttacking = true;
isSliding = true;
slideElapsedTime = 0;
input->setKeyUp(sf::Keyboard::D);
if (walk.getFlipped()) //if walk is flipped then flip the slide animation.
{
duck.setFlipped(true);
}
else duck.setFlipped(false);
currentAnimation = &duck; //using duck animation for teleport animation.
currentAnimation->animate(dt);
currentAnimation->reset();
setTextureRect(currentAnimation->getCurrentFrame());
if (isSliding)
{
target = sf::Vector2f(getPosition().x + 700 * hDir, getPosition().y); //set target location (current location + offset)
direction = target - getPosition(); //set direction to travel in (depends on current position)
if (getPosition() != target) //if not at same location...
{
move(direction*dt*scale); //...then move to target location.
}
}
playerStamina -= slideCost; //reduce the stamina
damage = 2; //set damage to be dealt to enemy.
//check collision and apply damage
}
}

Stockfish Engine breaks when loaded from a view controller instead of the app delegate iOS

I trying to implement the Stockfish UCI engine into a chess game app. Originally in the Stockfish iOS game the view controller that holds the board and the pieces is loaded from the app delegate. What I am trying to do is have a few more screens before navigating to the game. The problem I have is that the as soon as I load the board screen the game breaks in bitboard.cpp file with the message EXC_BAD_ACCESS(code=1, address=0x1fa80000) and a few times I have managed to load the pieces on the board and move one of them but then it brakes in the same place shown below on this line: occupancy[size] = b;
void init_magics(Bitboard table[], Bitboard* attacks[], Bitboard magics[],
Bitboard masks[], unsigned shifts[], Square deltas[], Fn index) {
int MagicBoosters[][8] = { { 969, 1976, 2850, 542, 2069, 2852, 1708, 164 },
{ 3101, 552, 3555, 926, 834, 26, 2131, 1117 } };
RKISS rk;
Bitboard occupancy[4096], reference[4096], edges, b;
int i, size, booster;
// attacks[s] is a pointer to the beginning of the attacks table for square 's'
attacks[SQ_A1] = table;
for (Square s = SQ_A1; s <= SQ_H8; ++s)
{
// Board edges are not considered in the relevant occupancies
edges = ((Rank1BB | Rank8BB) & ~rank_bb(s)) | ((FileABB | FileHBB) & ~file_bb(s));
// Given a square 's', the mask is the bitboard of sliding attacks from
// 's' computed on an empty board. The index must be big enough to contain
// all the attacks for each possible subset of the mask and so is 2 power
// the number of 1s of the mask. Hence we deduce the size of the shift to
// apply to the 64 or 32 bits word to get the index.
masks[s] = sliding_attack(deltas, s, 0) & ~edges;
shifts[s] = (Is64Bit ? 64 : 32) - popcount<Max15>(masks[s]);
// Use Carry-Rippler trick to enumerate all subsets of masks[s] and
// store the corresponding sliding attack bitboard in reference[].
b = size = 0;
do {
occupancy[size] = b;
reference[size] = sliding_attack(deltas, s, b);
if (HasPext)
attacks[s][_pext_u64(b, masks[s])] = reference[size];
size++;
b = (b - masks[s]) & masks[s];
} while (b);
// Set the offset for the table of the next square. We have individual
// table sizes for each square with "Fancy Magic Bitboards".
if (s < SQ_H8)
attacks[s + 1] = attacks[s] + size;
if (HasPext)
continue;
booster = MagicBoosters[Is64Bit][rank_of(s)];
// Find a magic for square 's' picking up an (almost) random number
// until we find the one that passes the verification test.
do {
do magics[s] = rk.magic_rand<Bitboard>(booster);
while (popcount<Max15>((magics[s] * masks[s]) >> 56) < 6);
std::memset(attacks[s], 0, size * sizeof(Bitboard));
// A good magic must map every possible occupancy to an index that
// looks up the correct sliding attack in the attacks[s] database.
// Note that we build up the database for square 's' as a side
// effect of verifying the magic.
for (i = 0; i < size; ++i)
{
Bitboard& attack = attacks[s][index(s, occupancy[i])];
if (attack && attack != reference[i])
break;
assert(reference[i]);
attack = reference[i];
}
} while (i < size);
}
I have not much experience and knowledge in C++ and I am struggling to figure out what is causing the issue.
I have managed to sort it out now! I figured that the game was still initialising while I was loading its view and this caused the whole issue, because the initialiser was running in the background! To sort it out I have made a loading screen and called the initialisers for the game there! And once it is all set up in the background I load the screen with the game!!! Hope my post helps someone in the future!

2D Platformer Collision Handling

I am trying to create a 2D platformer (Mario-type) game and I am some having some issues with handling collisions properly. I am writing this game in C++, using SDL for input, image loading, font loading, etcetera. I am also using OpenGL via the FreeGLUT library in conjunction with SDL to display graphics.
My method of collision detection is AABB (Axis-Aligned Bounding Box), which is really all I need to start with. What I need is an easy way to both detect which side the collision occurred on and handle the collisions properly. So, basically, if the player collides with the top of the platform, reposition him to the top; if there is a collision to the sides, reposition the player back to the side of the object; if there is a collision to the bottom, reposition the player under the platform.
I have tried many different ways of doing this, such as trying to find the penetration depth and repositioning the player backwards by the penetration depth. Sadly, nothing I've tried seems to work correctly. Player movement ends up being very glitchy and repositions the player when I don't want it to. Part of the reason is probably because I feel like this is something so simple but I'm over-thinking it.
If anyone thinks they can help, please take a look at the code below and help me try to improve on this if you can. I would like to refrain from using a library to handle this (as I want to learn on my own) or the something like the SAT (Separating Axis Theorem) if at all possible. Thank you in advance for your help!
void world1Level1CollisionDetection()
{
for(int i; i < blocks; i++)
{
if (de2dCheckCollision(ball,block[i],0.0f,0.0f)==true)
{
de2dObj ballPrev;
ballPrev.coords[0] = ball.coords[0];
ballPrev.coords[1] = ball.coords[1];
ballPrev.coords[2] = ball.coords[2];
ballPrev.coords[3] = ball.coords[3];
ballPrev.coords[0] -= ball.xspeed;
ballPrev.coords[1] -= ball.yspeed;
ballPrev.coords[2] -= ball.xspeed;
ballPrev.coords[3] -= ball.yspeed;
int up = 0;
int left = 0;
int right = 0;
int down = 0;
if (ballPrev.coords[0] < block[i].coords[0] && ballPrev.coords[2] < block[i].coords[0] && (((ball.coords[1] < block[i].coords[1]) || (ball.coords[3] < ball.coords[1])) || ((ball.coords[1] < block[i].coords[3]) || ball.coords[3] < block[i].coords[3])))
{
left = 1;
}
if (ballPrev.coords[0] > block[i].coords[2] && ballPrev.coords[2] > block[i].coords[2] && (((ball.coords[1] < block[i].coords[1]) || (ball.coords[3] < ball.coords[1])) || ((ball.coords[1] < block[i].coords[3]) || (ball.coords[3] < block[i].coords[3]))))
{
right = 1;
}
if(ballPrev.coords[1] < block[i].coords[1] && block[i].coords[1] < ballPrev.coords[3] && ballPrev.coords[3] < block[i].coords[3])
{
up = 1;
}
if(block[i].coords[1] < ballPrev.coords[1] && ballPrev.coords[1] < block[i].coords[3] && block[i].coords[3] < ballPrev.coords[3])
{
down = 1;
}
cout << left << ", " << right << ", " << up << ", " << down << ", " << endl;
if (left == 1)
{
ball.coords[0] = block[i].coords[0] - 18.0f;
ball.coords[2] = block[i].coords[0] - 2.0f;
}
else if (right == 1)
{
ball.coords[0] = block[i].coords[2] + 2.0f;
ball.coords[2] = block[i].coords[2] + 18.0f;
}
else if (down == 1)
{
ball.coords[1] = block[i].coords[3] + 4.0f;
ball.coords[3] = block[i].coords[3] + 20.0f;
}
else if (up == 1)
{
ball.yspeed = 0.0f;
ball.gravity = 0.0f;
ball.coords[1] = block[i].coords[1] - 17.0f;
ball.coords[3] = block[i].coords[1] - 1.0f;
}
}
if (de2dCheckCollision(ball,block[i],0.0f,0.0f)==false)
{
ball.gravity = -0.5f;
}
}
}
To explain what some of this code means:
The blocks variable is basically an integer that is storing the amount of blocks, or platforms. I am checking all of the blocks using a for loop, and the number that the loop is currently on is represented by integer i.
The coordinate system might seem a little weird, so that's worth explaining.
coords[0] represents the x position (left) of the object (where it starts on the x axis).
coords[1] represents the y position (top) of the object (where it starts on the y axis).
coords[2] represents the width of the object plus coords[0] (right).
coords[3] represents the height of the object plus coords[1] (bottom).
de2dCheckCollision performs an AABB collision detection.
Up is negative y and down is positive y, as it is in most games.
Hopefully I have provided enough information for someone to help me successfully. If there is something I left out that might be crucial, let me know and I'll provide the necessary information. Finally, for anyone who can help, providing code would be very helpful and much appreciated.
Thank you again for your help!
Edit 2: I have updated my code with a new algorithm that checks where the ball was previously before collision. Corner cases work on that single platform correctly now, and when I have a wall of objects, I can slide against it correctly now. The only remaining problem is that there is a small jittering effect that happens when I am on the ground, where the ball is constantly going up and down as if it is being pulled by gravity and then the ball falls back into the object again.
Edit: Here is a URL to an image trying to show the kinds of problems I am having:
http://img8.imageshack.us/img8/4603/collisionproblem.png
In case the explanation in the picture doesn't make too much sense, the ball cannot move left past the corner of an object unless I jump over it. However, the ball can move right, but it gets repositioned to the right of the object while moving, which is not needed. This creates a skipping movement essentially, where it appears as the the ball is skipping over half of the object or so when I move right. If this doesn't make sense, please ask me and I'll try to clarify more.
One problem with your code is that you only detect situations like this:
If the circle happens to be fully inside the block, you don't reposition at all. And that's a problem.
You're trying to think about your simulation as if it were continuous, but keep in mind it's discrete. In general, if you only look at the current state of the ball, you really cannot know which side it collided with. Look at these two possibilities:
The first solution that comes to mind is to look at the last position of the ball as well; more precisely, look at the delta vector. See if the delta vector intersects a wall. If it does, reposition in an axis-aligned direction towards the wall intersected by the delta vector.
Edit: When I said "delta vector", I forgot that you're moving a square and not a single point. So, if you just look at the delta vector of the top-left corner, that's not going to be enough because it may not detect that part of the ball entered a block. Instead, you can look at the delta vectors of all 4 corners.