15 - Drawing a Starfield (Part 4)

PART FOUR.

A 3D bob starfield is a little more involved than a dot starfield, but still quite an easy thing to create using CODEF. To make it even easier, I made a new library specifically for this purpose. 

Add the following line into your SCRIPT code section, after the main CODEF_CORE.JS call.


<script src="http://codef.namwollem.co.uk/JS/CODEF/codef_3dbobstarfield.js"></script>

That will bring the script into play, and next we start to define the starfield we want, give it properties, and finally draw it onto your canvas.
After you have defined your canvas in your case, you need to define the bob sprite used in the starfield.

var bob=new image('http://codef.namwollem.co.uk/files/ball_white.png');

Next, in the INIT section, we have set command to these parameters.


initStars(256,32);
This defines a 3D bob starfield, and sets how many bob sprites will be used, and lastly the maximum bit depth of the 3D effect as it travels towards you!
In this example we are asking for 256 bobs, and 32 pixels of depth.


Finally, we call the command to draw the starfield on the canvas.


do3dbobstarfield(mycanvas,320,240);

This command draws our 3D bob starfield to the canvas of choice, in this case, 'mycanvas', as we detail the centre position of the canvas (as we have a canvas of 640 by 480, the centre is 320 by 240).
You can see the entire script and HTML below, and see it in action here.



<!DOCTYPE HTML>

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>3D BOB STARFIELD</title> 

<script src="http://codef.namwollem.co.uk/JS/CODEF/codef_core.js"></script> 
<script src="http://codef.namwollem.co.uk/JS/CODEF/codef_3dbobstarfield.js"></script>

<script> 

var mycanvas;

var bob=new image('http://codef.namwollem.co.uk/files/ball_white.png');
// MUST use this variable and name

function init(){
mycanvas=new canvas(640,480,"main");

initStars(256,32);

go();
}

function go(){
mycanvas.fill('#000000');

do3dbobstarfield(mycanvas,320,240);

requestAnimFrame( go );
}

</script> 

</head> 
<body onLoad="init();">
<body bgcolor="#000000">
<br>
<center>
<div id="main"></div><br>
</center>
</body> 

</html>

No comments:

Post a Comment