Jump to content

Shooting circus cannon ball through a hoop (ball + cannon tube rotation/orientation alignment question)


Recommended Posts

Probably some easy question... but I've been struggling too long with the math.

Does anybody know how to compute the Linear Velocity (world space) of a Circus Cannon Ball based on the Cannon Tube mesh orientation?

In this case I use positive Y axis of cannon tube as 'forward', but in general I use the local Z axis as forward (to adhere to the definitions of BABYLON.Vector3.Forward() etc.).

Once I know how to dynamically compute the (normalized) direction of the tube, I can then scale this vector with the cannon's shooting power (e.g. longer fire button press results in farther shooting). And add some random vector noise to make easy ball have a slightly different path each time.

Please note that the tube is a child mesh on purpose so the orientation needs to be translated to world first.

Here's the playground so far:


The solution to this question will probably be useful for anyone else who is creating some kind of ballistic shooter game (not first person).

I noticed that all physics vectors are in world space only so therefore I am looking for these kind of transformations to roll up local mesh orientation to world physics direction.



P.S. The cannon is set to auto-fire but you can use SPACE for fire as well, and [ and ] to turn the cannon.

shoot cannon ball through the hoop.png

Link to comment
Share on other sites

Hiya QH.  Cool project/playground!


1.  I switched to the Oimo physics engine, instead of the default CannonJS physics engine (lines 29/30).  It's just my personal preference.  CannonJS causes annoying show-stopper "physics not enabled" errors for me, after a few edits in the playground.

2. Switched to arcRotateCamera... also for personal reasons.  (In my Firefox, freeCam up/down cursor... causes playground 1-line html scroll).  Spacebar also causes his one-line scroll for me.   So, that's why I increased auto-fire rate a bit... so I could avoid using my spacebar.  Someday I will figure out WHY up/down arrows and spacebar cause these playground problems, I hope.

3.  Established a "direction vector" in line 110.  There are "math ways" of making a direction vector, but... easiest for me is to position/parent an invisible box in front of cannontube, then use a subtraction method.  Activate line 112 to see the direction vector on JS console... for each shot.  The first parameter of an applyImpulse call... needs a direction vector.  Its "magnitude" is the power.  You may wish to do a little web-reading about direction vectors and magnitudes... they are interesting.  The scale in line 114 ... is a direction vector magnitude amplifier/limiter.  Scaling a direction vector keeps the actual direction the same, but makes the direction vector longer/shorter... sort-of.  :) Sort of an AMOUNT of direction.  :)

4.  Used applyImpulse in line 114, but I think setLinearVelocity and/or applyForce would also work fine.

5.  Remarked-out line 107.  Rotating the cannonball/bullet has no real effect on its physics flight-angle.  (But it might be cool if it did, eh?)

6.  Added the 'u' and 'd' keys for cannontube up/down rotation... needed to do testing on that, to make sure my dir vector was working correctly.

7.  Added a power setting in line 120... used in all firebullet calls.

8.  Temporarily increased auto-fire rate in line 124.... for testing.

Line 49 sets the visibility of itarg... the target box used to derive a direction vector (dir).  itarg will likely be invisible for final product.

Anyway, goof around with this... see what you like or hate... ask questions if you like (perhaps use @ wingnut to ping me for questions - but remove space before the 'w')

If you switch back to CannonJS in lines 29/30 area, you will have to reduce power a BUNCH, I think.  Our two main physics plugins do not have good applyImpulse crossover at this time.  Maybe better luck with applyForce or setLinearVelocity.

Others are math-smarter than I, and might have better versions/comments.  I hope I have been helpful.

Link to comment
Share on other sites

Oops, Oimo does not have a "meshImpostor" so you can't shoot balls thru the ring.  Let's try another version, using CannonJS physics plugin/engine.


There we go... CannonJS active, ring meshImpostor working.  This uses applyForce instead of applyImpulse.  Power increase was needed.

Hotkeys same as previous...  [ & ] to turn left/right, 'u' and 'd' keys to raise/lower pitch/elevation, spacebar to fire.  Seems to be working ok... but...

...does anyone see a slight cannonball turn to the right... upon first ground-bounce?  *shrug*  Perhaps it is an optical illusion.  :)

Link to comment
Share on other sites

Hi Wingnut,

Thanks for your responses!

What an excellent idea to use an imaginary "crosshair" box in front of the cannon tube. This can be very useful for a player commanding the circus cannon to visually represent the 'firing power setting'.  ?

The playground circus cannon http://playground.babylonjs.com/#R8ZH46#4 seems to be working as desired. This is a useful solution.

The direction of bullets can be a bit deceiving because of the 3d perspective.

I'll implement your suggested approach into my game.

For some reason the bullet shot from the cannon in my game (not in the playground) now crashes into an imaginary physics wall (not the crosshair though) before reaching the target 'hoop'... ah well, the next challenge awaits ?



Link to comment
Share on other sites

Sounds good, QH!  I'm glad.  Yeah, maybe change itarg to be a plane, with target reticle texture.  :)

Umm... the invisible physics wall... MIGHT be caused by a sort-of-recent change to pivots.  Please ensure you are using the latest BJS and approved version of CannonJS.

hmm.  I'll keep thinking about WHY there is an invisible physics wall.

Are you using a different "ring"?  Perhaps a ring... created with modeling software (3dsMax/Blender/etc)?

hmm.  Try shooting thru the ring from the opposite side, perhaps.  See if invisible wall is hit AFTER the ball goes thru ring?

Position ring further from cannontube.  Did invisible wall move, too?   *shrug*  Just some testing ideas.

For a bit more realism, you may wish to position each ball... at the "front" of the cannontube... just barely inside the tube (and fire from there).

Link to comment
Share on other sites

Yeah I changed the alpha targeting box to a plane mesh to save on vertices as well ?

Positioning the starting point of the bullet at the end of the gun tube will make it even more realistic indeed.

Anyway the solution works very nicely. See the image from my BabylonJS Model Train Simulator game.

Hint: The gun is stationed on a train wagon. When I move the train (and thus the gun) the trajectory of the bullets also change with it. See the painted arrows.

Any potential 'train robbers' wouldn't be happy any more now we've got the mounted gun working haha ?

Invisible collider walls

The invisible (vertical and horizontal) collider walls seem to be a bug or thingee in the test level I am using for the cannon demo in my game.

I think it has to do with the collider on the ground mesh, which is a heightmap with post process CSG.

For BoxImpostor it takes the min+max height of the heightmap as the collision bounds...
HeightmapImpostor crashes the browser (the heightmap isn't square and may contain holes, which may be the reason for this).
MeshImpostor and PlaneImpostor same effect as BoxImpostor.

I'm using cannonjs from

I'm not sure yet but the wrongly computed/crashing collider might be a bug in the framework. But then I want to be really sure before reporting it as a bug and create a playground sample first.

cannon physics gun bullet orientation babylonjs model train simulator.png

Link to comment
Share on other sites

5 hours ago, QuintusHegie said:

the ground mesh, which is a heightmap with post process CSG.

Hi QH!  Man that's a cool scene/sim... I love it.  Is the CSG used to make the holes in the terrain?  I suspect so.

Yeah, I would definitely try a version WITHOUT the CSG terrain, and see if the invisible collider goes-away.  Worth a test, huh?

I don't do CSG very often or well, but I think you make mesh that can be used as "cookie-cutters" (bool subtract)... for holes.

Make sure that those cookie-cutter mesh... are low-height.  Make them just as short as is-possible.  I'm not sure if that will change anything, but maybe.

It might also be interesting to do terrain.showBoundingBox = true, and see if THAT is much bigger/taller than it should be.

Just thinkin'.

Turning Train Gun

With the train gun/railcar turning, is there an unwanted/unexpected effect happening?  Yep, targeting the cannon while riding on a Y-turning flatcar... yeah... good fun!  Track-side deer and cars are already difficult to shoot, but on a moving train... MUCH more difficult.  heh.

You could try something in the renderLoop... like... cannonfoot.rotation.y += guncar.rotation.y;  That might keep the gun aimed at a single direction, even when the guncar is changing its Y-rotation.

Also, keep in mind that you have a type of auto-targeting feature.  You'll likely need a setCannonAimPerDirectionVector(directionVector).  That function would convert a direction vector... to a cannonfoot Y-rotation and a cannontube X-rotation.  (not an easy func to code, likely).  Remember that you can always get a direction-to-some-target... by using...

var autoAimDirVec = sometarget.position.subtract(cannontube.position);  You might need to swap those items... cannontube.position.subtract(sometarget.position);

And, you will need to do continuous auto-aiming in the renderLoop... if you want the gun to constantly "track" some track-side target.  You might be able to steal some code from BJS camera.setDirection.... for your setCannonAimPerDirectionVector(directionVector) function.  When using auto-aim, the trackside target replaces the itarg, in a way.  But you MUST aim the cannontube and cannonfoot before firing, or else the bullet will fire from the SIDE of the cannon.  The proper way... would be to fast-animate the cannonfoot and cannontube... to the new auto-aim orientation... and THEN allow firing or auto-fire.  (That 'fast-animate' playground is full of advanced slerpy stuff and quaternion rotation... gruesome 'look-At' hacking.  You need to rotate TWO mesh - foot and tube... not just a single cone.  erf!  Tube gets the x-rotation, foot gets the Y-rotation.)

Sort of need... click on something along the tracks.  When that happens, directionVector starts being constantly calculated... between clicked mesh.... and cannontube.  Now we have a continuous direction-to-target vec3.  Then, perhaps the auto-aim, auto-aim locked, and auto-aim/lock/fire buttons (3 buttons)... appear on-screen.  FUN! 

A click on ANY of the three buttons... swings the cannonfoot around, and adjusts the cannontube elevation, and gets ready for firing.  The targeting reticle should be good... I think it is parented to cannontube.  If either 'locked' button was pressed, you must constantly (renderLoop) call setCannonAimPerDirectionVector(directionVector)... always using the freshest directionVector.  Target tracking.  Coooooool.  :)  Kind of demented.  heh.  A GOOD auto-tracker would turn OFF the fire button... when firing would result in blasting your own boxcars/consist/rolling-stock.  :D

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...