borders of sprite with custom draw
hermes

I was looking at the flow example, and it inspired me to go ahead and write some custom draw functions for my sprites. Just for fun, I want to see if I can create some interesting visual effects in this way.

 

I have a problem at the moment, and I can't understand why. It's a long story, but I've managed to reduce the problem to this: if I draw the borders of a simple rectangle (which is as big as the size of my sprite), then when I move my sprite, I get some visual problems. It's as if it didn't erase the borders from the previous position, it just draws the sprite at the new position, on top of the old one.

 

But if I use the draw function that comes with wade (wade.drawFunctions.drawRect_), it does the same thing but works perfectly! I can't understand why mine doesn't work... here's my code, if you can help with this it would great!

var position = this.getPosition();var size = this.getSize();context.strokeColor = 'red';context.strokeRect(position.x - size.x / 2, position.y - size.y / 2, size.x, size.y);context.stroke();
All 2 Comments
Gio

It looks like you aren't taking the line width into account, so your custom draw function ends up drawing slightly outside the bounding box of the sprite. You want to make sure that you always draw inside the bounding box of your sprite, or you may encounter visual problems like the one you've described. Drawing a rectangle that's smaller than your sprite wouldn't be a problem.

 

If you really want to draw a rectangle that's exactly as big as your sprite:

 

Ideally, you want to add a half-pixel margin as well (just in case the browser decides to do some anti-aliasing at the edge of the rectangle you're drawing - Firefox and Chrome do this). But of course you're drawing in world units, not in screen units, i.e. the layer that contains your sprite may have any transformation, for example the camera may have been moved closer, etc. So you need to convert half a pixel into world units, then consider that in your call to strokeRect:

var e = wade.screenUnitToWorld(this.getLayerId()) * 0.5;context.lineWidth = borderWidth;context.strokeRect(position.x - size.x / 2 + borderWidth + e, position.y - size.y / 2 + borderWidth + e, size.x - borderWidth * 2 - e, size.y - borderWidth * 2 - e);

However this will only work if the sprite doesn't have a rotation - if a rotation is involved, you would have to take that into account too.

 

It's fairly advanced stuff, which is why we provide those ready-made draw functions :)

hermes

Thanks it makes sense. I don't really want to draw a simple rectangle, it was just a test case. Your explanation makes sense, I think I can do what you said to fix my problems. Yeah rotations would be more difficult, but I'm not caring about those just yet.

Post a reply
Add Attachment
Submit Reply
Login to Reply