Ok, thats my old code, but does anyone have any better code for distuingishing hit detection between two rectangles?This code tells you if the center of the first object is anywhere inside the bounds of the second object(return true).Code: Select all
function bulletCollide(Obj1X, Obj1Y, Obj1MX, Obj1MY, Obj2X, Obj2Y, Obj2MX, Obj2MY) Obj1MidX=Obj1X+(Obj1MX/2) Obj1MidY=Obj1Y+(Obj1MY/2) Obj2MaxX=Obj2X+Obj2MX Obj2MaxY=Obj2Y+Obj2MY if Obj1MidX<Obj2MaxX+1 and Obj1MidX>Obj2X-1 and Obj1MidY<Obj2MaxY+1 and Obj1MidY>Obj2Y-1 then return true end return false end
Obj1X is the starting X, Obj1XM is the is the width of the rectangle/square and so on for the others.
Best way for collision pt. 2
Moderators: Shine, Insert_witty_name
-
- Posts: 64
- Joined: Fri Jul 15, 2005 11:44 pm
Best way for collision pt. 2
-
- Posts: 64
- Joined: Fri Jul 15, 2005 11:44 pm
Code: Select all
int sprite_colide(SDL_Rect *rc, SDL_Rect *rc2) {
int i,z;
for( i = rc->x; i < rc->x+rc->w; i++) {
for(z = rc->y; z < rc->y+rc->h; z++) {
if(i >= rc2->x && i <= rc2->x+rc2->w && z >= rc2->y && z <= rc2->y+rc2->h) return 1;
}
}
return 0;
}
rc->w is the width of the image in pixels, rc->x would be the x location of the first pixel and so on.
Would that code be suffucient if converted to LUA? I can convert it myself, but it may take awhile, but if someone can read that code and make a LUA version of it for me, I'd be most greatful as I hate working with LUA for loops(Having no brackets and such give me a headache...)
Code: Select all
--attack area
-- x1---x2
-- | | player
-- | X | X=centre
-- | | --> collision when centre is hit by centre of enemy
-- y1---y2
collision=1
x1=xpos
x2=xpos+playerWidth
y1=ypos
y2=ypos+playerHeight
e_x1=enemyX
e_x2=enemyX+enemyWidth
e_y1=enemyY
e_y2=enemyY+enemyHeight
x_centre=xpos+( (x2-x1)/2 )
y_centre=ypos+( (y2-y1)/2 )
e_x_centre=enemyX+( (e_x2-e_x1)/2 )
e_y_centre=enemyY+( (e_y2-e_y1)/2 )
if math.abs(e_x_centre-x_centre)>=enemyWidth/2 then collision=0
elseif math.abs(e_y_centre-y_centre)>=enemyHeight/2 then collision=0
end