SDL trouble with side collision detection

Hi, i'm working on a sidescroller game and for now Igot trouble with the collision form both right and left side. Top and bottom collision seems to work properly.

I got this function to determine if a collision occur in a Base class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
bool Base::collision(SDL_Rect *rect1 , SDL_Rect *rect2)
{
	if(rect1->y +rect1->h <= rect2->y)
	{
		return false;
	}
	if(rect1->y >= rect2->y + rect2->h)
	{
		return false;
	}
	if(rect1->x +rect1->w <= rect2->x)
	{
		return false;
	}
	if(rect1->x >= rect2->x +rect2->w)
	{
		return false;
	}
	
	return true;
}



And now on my move function I check if there is a collision with a tile of the map that is not 0(nothing) and i need to know wich kind of collision it is.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
	bool falling= true;
	int start = (Base::coord.x - (Base::coord.x%Base::tileSize))/Base::tileSize;
	int end = (Base::coord.x + Base::coord.w +(Base::tileSize -(Base::coord.x + Base::coord.w)%Base::tileSize))/Base::tileSize;
	if (start<0)
	{
		start = 0;
	}
	if (end>map[0].size())
	{
		end = map[0].size();
	}
	for(int i=0;i<map.size();i++)
	{
		for(int j=start;j<end;j++)
		{
			if(map[i][j] != 0)
			{
				SDL_Rect destination ={j*Base::tileSize - Base::coord.x, i*Base::tileSize, Base::tileSize, Base::tileSize};
				if(collision(&box, &destination))
				{
					falling = false;
					//top collision
					if( box.y + box.h >= destination.y  )
					{
						ground = true;
						yVel = 0;
						
					}

					//bottom collision
					else if(box.y <= destination.y + destination.h)
					{
						 
						yVel = 5;
					}
					// left collision
					if( box.x + box.w >= destination.x  &&  box.y + box.h <= destination.y)
					{
						xVel = -1;
						
					}
					//right collision
					else if(box.x <= destination.x + destination.w && box.y + box.h <= destination.y)
					{
					xVel = 1;
					
					}

			
				}
			}


		}
	}

	if(falling && !jump)
	{
		yVel = 4;
	}

	if(  jump && yVel < 5)
	{
		yVel += 1;

	}

	else
	{
		jump = false;
	}

	box.x += xVel;

	box.y += yVel;
}



Like I said right and left collision seem to be the problem. Some help would be greatly appreciated :)
Last edited on
Topic archived. No new replies allowed.