Arena Shooter tutorial

Step 3: Containers

Now it is time to decorate the Arena to bounce the rocket back if it hits the wall. The BorderHitDecorator registers a method that affects its children (in the DOM), which is a definition of game Container. In addition to it, we set the style position: relative, so the children absolute position is calculated within the Arena contents. The children can then implement methods hitBorderH (which is called when it hits border in horizontal direction, left or right) and hitBorderV (for vertical border hit, top and down). They get a parameter -1 for left (resp. top) wall or +1 for right (bottom) wall. To prevent error in cases when some children don't implement these methods, we use Optional chaining (?.) operator.

BounceDecorator below implement these methods in target object in a way to perform these methods in a way to bounce back keeping the bounce angle. In the last step 4 we will implement bullets, which won't bounce (albeit that would be fun), but crash in CrashDecorator.

BorderHitDecorator = o => o.register( _=> [...o.children].forEach( C => ( C.offsetLeft < 5 && C.hitBorderH?.call(0,-1), C.offsetLeft > o.offsetWidth - 15 && C.hitBorderH?.call(0,1), C.offsetTop < 5 && C.hitBorderV?.call(0,-1), C.offsetTop > o.offsetHeight - 15 && C.hitBorderV?.call(0,1) ))); BounceDecorator = o => { o.hitBorderH = d => (o.angle = - o.angle, o.rotate?.call(0,0), = o.offsetLeft - 10*d + "px"); o.hitBorderV = d => (o.angle = 180 - o.angle, o.rotate?.call(0,0), = o.offsetTop - 10*d + "px"); }; RenderDecorator(Arena); BorderHitDecorator(Arena); BounceDecorator(R);