Create a Flash Ball game with visual from above – Flare3D version

Read all posts about "" game

If you are a long time reader, you should remember the Create a Flash ball game with visual from above tutorial published almost four years ago. I also made a game out of it, Tileball, probably too hard.

Now I am showing you how to do the same thing using Flare3D.

What’s the point in using a 3D engine to make a 2D game? The animation of the rolling ball, for instance.

Let’s see this script:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Vector3D;
	import flare.basic.*;
	import flare.primitives.*;
	import flare.system.Input3D;
	import flare.materials.*;
	import flare.utils.*;
	import flare.collisions.*;
	public class flareball extends Sprite {
		private var scene:Scene3D;
		private var ball:Sphere;
		private var camTarget:Sphere;
		private var sphereSpeed:Vector3D = new Vector3D();
		private var friction:Number=0.99;
		private var ballMaterial:WireframeMaterial=new WireframeMaterial("",1,0x004400,1,0x00aa00,1);
		private var ballOutMaterial:WireframeMaterial=new WireframeMaterial("",1,0x440000,1,0xaa0000,1)
		private var collisions:RayCollision=new RayCollision();
		public function flareball() {
			var track:Cube;
			var trackMaterial:WireframeMaterial=new WireframeMaterial("",1,0x000044,1,0x000088,1);
			scene=new Scene3D(this);
			ball=new Sphere("",5,10,ballMaterial);
			camTarget=new Sphere("",1);
			scene.addChild(ball);
			scene.addChild(camTarget);
			track=new Cube("",50,50,250,1,trackMaterial);
			track.setPosition(0,-25.5,0);
			scene.addChild(track);
			collisions.addCollisionWith(track);
			track=new Cube("",250,50,50,1,trackMaterial);
			track.setPosition(150,-25.5,100);
			scene.addChild(track);
			collisions.addCollisionWith(track);
			track=new Cube("",250,50,50,1,trackMaterial);
			track.setPosition(150,-25.5,-100);
			scene.addChild(track);
			collisions.addCollisionWith(track);
			track=new Cube("",50,50,250,1,trackMaterial);
			track.setPosition(300,-25.5,0);
			scene.addChild(track);
			collisions.addCollisionWith(track);
			scene.camera.setPosition(0,200,0);
			scene.camera.lookAt(0,0,0);
			scene.addEventListener(Scene3D.UPDATE_EVENT,updateEvent);
		}
		private function updateEvent(e:Event):void {
			if (Input3D.keyDown(Input3D.UP)) {
				sphereSpeed.z+=0.25;
			}
			if (Input3D.keyDown(Input3D.LEFT)) {
				sphereSpeed.x-=0.25;
			}
			if (Input3D.keyDown(Input3D.DOWN)) {
				sphereSpeed.z-=0.25;
			}
			if (Input3D.keyDown(Input3D.RIGHT)) {
				sphereSpeed.x+=0.25;
			}
			sphereSpeed.scaleBy(friction);
			ball.x+=sphereSpeed.x;
			ball.z+=sphereSpeed.z;
			ball.rotateZ(-sphereSpeed.x*5,false);
			ball.rotateX(sphereSpeed.z*5,false);
			if(collisions.test(new Vector3D(ball.x,ball.y,ball.z),new Vector3D(0,-1,0))){
				ball.setMaterial(ballMaterial);	
			}
			else{
				ball.setMaterial(ballOutMaterial);
			}
			camTarget.x=ball.x;
			camTarget.z=ball.z;
			Pivot3DUtils.setPositionWithReference(scene.camera,0,200,0,camTarget,0.1);
		}
	}
}

Lines 5-10: import required Flare3D classes

Line 12: defines a Scene3D variable. Scene3D is the world which will contain our 3D environment.

Line 13: defines a Sphere variable, used to create the ball

Line 14: defines another Sphere variable, which will be used to create the target the camera will track. It’s not mandatory to create it as a sphere, we just need a body to act as a camera tracker.

Line 15: sphereSpeed is the vector containing x and z speeds of the ball. y has not speed since it’s a 2D game with the visual from above.

Line 16: we also need a friction to simulate some kind of physics.

Lines 17-18: creation of two different wireframe materials to be applied to the ball. ballMaterial will be applied when the ball is on the track, ballOutMaterial when it’s out of the track. It’s just to give a visual feedback.

Line 19: a RayCollision variable. It will be used to see if the ball is on the track.

Line 21: defines a Cube variable, which will be used to build the track. I won’t use squared tiles like in the original engine this time, I’ll just build a big “O” with four rectangular tiles.

Line 22: creates the track material.

Line 23: creates the scene.

Line 24: creation of the ball itself. The four arguments are the name, the radius, the number of segments into which the sphere is to be divided and the material.

Line 25: this is the dummy sphere which will act as camera target.

Lines 26-27: adds both spheres to the scene.

Line 28: we start building the track, cube by cube. The arguments are the name, the width, the height, the depth, the number of segments the cube will have on each face and the material.

Line 29: sets the position of the cube, in the (x,y,z) space.

Line 30: adds the cube to the scene.

Line 31: very important line: adds the newly added cube to the list of objects we have to check for the collision.

Lines 32-43: construct the rest of the track.

Lines 44-45: set up the camera position and target, using (x,y,z) coordinates.

Line 46: Flare3D listener to be triggered once there is something to update. It will call updateEvent function.

Lines 49-51: increase z speed if the player pressed UP arrow key.

Lines 52-60: same concept applied to LEFT, DOWN and RIGHT arrow keys.

Line 61: applies friction using ScaleBy method.

Lines 62-63: update ball position according to the speed.

Lines 64-65: update ball rotation according to the speed. The second argument has to be set to true to rotate respecting current orientation, or false to rotate according to orientation relative to parent (our case).

Line 66: the core of collision detection. From the origin of the ball Vector3D(ball.x,ball.y,ball.z) we fire a ray downward Vector3D(0,-1,0) looking for any of the objects previously inserted with addCollisionWith method. Then we show the green ball (line 67) if there is a collision (the ball is on the track) or the red ball (line 70) otherwise.

Lines 72-73: update the position of camTarget to make it have the same position of the ball.

Line 74: moves the camera to place it in the same coordinates as the ball, just at an higher position.

This is the result:

Move the ball tapping arrow keys. The ball will be green when correctly on track, red otherwise.

Download the source code. How would you improve the prototype? Anyone willing to convert it using Away3d?

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers