c# - Rectangles don't collide correctly -
as can see on top corner says col: false/true. if player bounds , tiles solids. rectangles tiles , players checked if intercept each-other. looks working right? nope. more closely.
the bottom right corner needs inside tiles count.
now let's code used understand problem.
player bounds (rectangle)
playerbounds.width = 32; playerbounds.height = 64; playerbounds.x = (int)this.position.x; playerbounds.y = (int)this.position.y;
tile bounds (rectangle)
newtile.bounds = new rectangle(x * tile_size, y * tile_size, tile_size, tile_size);
now onto how detects it:
for (int x = 0; x < tilemap.map_width; x++) { (int y = 0; y < tilemap.map_height; y++) { if (tm.tile[x, y].bounds.intersects(playerbounds)) { if (tm.tile[x, y].getsolid()) { colliding = true; } else { colliding = false; } } } }
move
public void move(vector2 pos) { (int = 0; < speed; i++) { position += pos; } }
i have used breakpoints @ collision detection loop. , rectangle covers character , tiles.
you overriding previous collisions in loop. result solid-state of last tile intersects player. try adaptation this:
colliding = false; (int x = 0; x < tilemap.map_width; x++) { (int y = 0; y < tilemap.map_height; y++) { if (tm.tile[x, y].bounds.intersects(playerbounds) && tm.tile[x, y].getsolid()) { colliding = true; break; } } if(colliding) break; }
a more efficient approach check tiles intersect. since use simple axis-aligned rectangles, set of intersecting tiles should not hard calculate.
Comments
Post a Comment