This is part II of Flash game tutorial ‘Willy The Whale’. Previous articles:
1) Introducing Willy The Whale
In order to make things a little more complicated I need some bad fishermen with whale soup on their mind. For now, I don’t have to illustrate some advanced design, I just need movie clip holders, which means any kind of graphics.
Fisherman’s boat consist out of two parts, rectangle movie clip and separate movie for deadly spear. At any time I want my spear to be static to the boat, so next code is used to do just that:
// spear actions
spear_mc.onEnterFrame = function() { this._x = fishermen_mc._x - 30; this._y = fishermen_mc._y - 10;}
I will also temporary give the boat some basic movement, nothing fancy, just to have some action.
// fishermen actions
fishermen_mc.onEnterFrame = function() { if(this._x < (Stage.width + this._width /2)) { this._x += 3; }else{ this._x = -135; }}
Advanced Movement
One way to control variables is to make single Object to hold different values. Our object is called wv, but can name it what ever you like, just make sure to change every appearance through entire code. Now let’s make our object:
var wv:Object = new Object();wv.speed = 0.5;wv.vx = 0;wv.vy = 0;wv.friction = 0.95;wv.maxspeed = 3;
Remember that all code is placed inside first and only main Timeline frame.
Ok, so let’s explain our object. All those values are initial values, speed initial value is 0.5, friction 0.95 and x and y components are set to 0. Maxspeed value will allow our whale not to go crazy with unlimited speed, but to keep it under value 3.
Last thing is to change our code from previous article and make it work with our newly created object. We will also include alpha changes (will become important later) and we will allow Willy to have 2 sides, one when moving to the left and one when moving to the right. Here is the code:
// whale movement
willy.onEnterFrame = function() {
if (Key.isDown(Key.LEFT)) { wv.vx -= wv.speed; willy.gotoAndStop(1); } else if (Key.isDown(Key.RIGHT)) { wv.vx += wv.speed; willy.gotoAndStop(2); } else wv.vx *= wv.friction;
if (Key.isDown(Key.UP)) wv.vy -= wv.speed; else if (Key.isDown(Key.DOWN)) wv.vy += wv.speed; else wv.vy *= wv.friction;
//update whale position if (willy._x > Stage.width) willy._x = Stage.width;
if (willy._x < 0) willy._x = 0;
if (willy._y > Stage.height) willy._y = Stage.height;
if (willy._y < 150) willy._y = 150;
willy._x += wv.vx; willy._y += wv.vy;
//limit speed if (wv.vx > wv.maxspeed) wv.vx = wv.maxspeed; else if (wv.vx < -wv.maxspeed) wv.vx = -wv.maxspeed;
if (wv.vy > wv.maxspeed) wv.vy = wv.maxspeed; else if (wv.vy < -wv.maxspeed) wv.vy = -wv.maxspeed;
willy._x += wv.vx; willy._y += wv.vy; willy._alpha = (350 - willy._y) / 2;}
Special thanks for inspiration goes to ASGamer