Actionscript 3 - Rotate symbol? - actionscript-3

I'm working on a tutorial on youtube to learn some action-script 3. I've got my finished product which is basically a symbol that is known as ball and it has an instance called _ball. The finished product from the tutorial is shown here.
Tutorial Video - Youtube
So basically what I want to achieve is the ball to rotate, depending on which way the ball is moving how would I go about achieving this? I'm new to action-script so some code samples would be appreciated or a in depth explanation.
Incase anyone wants a copy of the code - this is it - I've edited it about in some ways but it doesnt effect much.
package
{
import flash.display.MovieClip
import flash.text.TextField
import flash.events.Event
import flash.events.MouseEvent
public class DocumentMain extends MovieClip
{
public const GRAVITY:Number = 2; // Declaring a const variable known as gravity
public const BOUNCE:Number = 0.8;
public const HIT:Number = 15;
public var _bounces:TextField;
public var _highscore:TextField;
public var _ball:Ball;
private var _vx:Number; // Declaring a variable known as _vx
private var _vy:Number; // Declaring a variable knwon as _vy
public function DocumentMain(): void
{
_vx = Math.random(); // Initalising _vx
_vy = Math.random(); // Initalising _vy
_ball.buttonMode = true;
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
}
private function enterFrameHandler (e:Event):void
{
// Gravitate the Ball
_vy += GRAVITY; // The ball is effected by gravity each frame
// Move The Ball
_ball.x += _vx;
_ball.y += _vy;
// Check Stage Boundaries For Collisions
checkBoundaryCollision();
}
private function mouseDownHandler (e:MouseEvent):void
{
// Hit the ball if it has been clicked
if (e.target == _ball)
{
hit(e.target.mouseX, e.target.mouseY);
}
}
private function checkBoundaryCollision():void
{
var left:Number;
var right:Number;
var bottom:Number;
var top:Number;
left = _ball.x - (_ball.width / 2);
right = _ball.x + (_ball.width / 2);
bottom = _ball.y + (_ball.height / 2);
top = _ball.y - (_ball.height / 2);
if (left < 0 && _vx < 0)
{
_ball.x = (_ball.width / 2)
_vx *= -1;
}
else if (right > stage.stageWidth && _vx > 0)
{
_ball.x = stage.stageWidth - (_ball.width / 2)
_vx *= -1;
}
if (top <= 42.70 && _vy < 0)
{
_ball.y = (_ball.height / 2)
_vy *= -1;
}
else if (bottom > stage.stageHeight && _vy > 0)
{
_ball.y = stage.stageHeight - (_ball.height/2)
_vy *= -BOUNCE;
_vx *= BOUNCE;
if (Number(_bounces.text) > Number(_highscore.text))
{
_highscore.text = _bounces.text;
}
_bounces.text = "0";
}
}
private function hit(hitX:Number, hitY:Number):void
{
// increment bounces
_bounces.text = String(Number(_bounces.text) + 1);
// Adjust vertical velocity
if (_vy > 0)
{
_vy *= -BOUNCE / 2;
}
_vy -= HIT;
//adjust horizontal veloity
if (_vx * hitX > 0)
{
_vx *= -BOUNCE;
}
_vx -= (hitX / _ball.width * HIT);
}
}
}

I can't test this right now, but it should be as simple as updating your enterFrameHandler to rotate the ball on each frame by a base value multiplied by the ball's x velocity:
public const ROTATION:Number = 1;
private function enterFrameHandler (e:Event):void
{
// Gravitate the Ball
_vy += GRAVITY; // The ball is effected by gravity each frame
// Move The Ball
_ball.x += _vx;
_ball.y += _vy;
// Rotate the ball each frame at a speed and direction
// related to the ball's current x velocity. A negative
// x velocity will result in a negative rotation.
_ball.rotation += ROTATION * _vx;
// Check Stage Boundaries For Collisions
checkBoundaryCollision();
}

Related

Actionscript 3.0 Mouse trail snake game logic

I am developing a game in actionscript 3.0 (adobe flash) similar to this https://www.tvokids.com/preschool/games/caterpillar-count. I have the code for dragging the head of the snake in the direction of the mouse. However, I do not know how do I add the body of the snake and make it follow the path of the head. Following is my code to drag movieclip in the direction of the mouse :
var _isActive = true;
var _moveSpeedMax:Number = 1000;
var _rotateSpeedMax:Number = 15;
var _decay:Number = .98;
var _destinationX:int = 150;
var _destinationY:int = 150;
var _dx:Number = 0;
var _dy:Number = 0;
var _vx:Number = 0;
var _vy:Number = 0;
var _trueRotation:Number = 0;
var _player;
var i;
createPlayer();
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
function createPlayer():void{
_player = new head();
_player.x = stage.stageWidth / 2;
_player.y = stage.stageHeight / 2;
stage.addChild(_player);
}
function onDown(e:MouseEvent):void{
_isActive = true;
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
}
function onMove(e:MouseEvent):void{
updatePosition(_player);
updateRotation(_player);
}
function onUp(e:MouseEvent):void{
_isActive = false;
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMove);
stage.removeEventListener(MouseEvent.MOUSE_UP, onUp);
}
function updatePosition(mc):void
{
// check if mouse is down
if (_isActive)
{
// update destination
_destinationX = stage.mouseX;
_destinationY = stage.mouseY;
// update velocity
_vx += (_destinationX - mc.x) / _moveSpeedMax;
_vy += (_destinationY - mc.y) / _moveSpeedMax;
}
else
{
// when mouse is not down, update velocity half of normal speed
_vx += (_destinationX - mc.x) / _moveSpeedMax * .25;
_vy += (_destinationY - mc.y) / _moveSpeedMax * .25;
}
// apply decay (drag)
_vx *= _decay;
_vy *= _decay;
// if close to target, slow down turn speed
if (getDistance(_dx, _dy) < 50)
{
_trueRotation *= .5;
}
// update position
mc.x += _vx;
mc.y += _vy;
}
function updateRotation(mc):void
{
// calculate rotation
_dx = mc.x - _destinationX;
_dy = mc.y - _destinationY;
// which way to rotate
var rotateTo:Number = getDegrees(getRadians(_dx, _dy));
// keep rotation positive, between 0 and 360 degrees
if (rotateTo > mc.rotation + 180) rotateTo -= 360;
if (rotateTo < mc.rotation - 180) rotateTo += 360;
// ease rotation
_trueRotation = (rotateTo - mc.rotation) / _rotateSpeedMax;
// update rotation
mc.rotation += _trueRotation;
}
function getDistance(delta_x:Number, delta_y:Number):Number
{
return Math.sqrt((delta_x*delta_x)+(delta_y*delta_y));
}
function getRadians(delta_x:Number, delta_y:Number):Number
{
var r:Number = Math.atan2(delta_y, delta_x);
if (delta_y < 0)
{
r += (2 * Math.PI);
}
return r;
}
function getDegrees(radians:Number):Number
{
return Math.floor(radians/(Math.PI/180));
}
The script below will not miraculously work on its own, however it has all the logic you need, well-explained. It makes a chain of any length follow its head by certain rules. I used the same principle here many years ago: http://delimiter.ru/games/25-lines/alone.html
// This one will represent the Mouse position.
var Rat:Sprite = new Sprite;
// The ordered list of chain elements.
// It all starts with the Mouse.
var Snake:Array = [Rat];
// Call this one each time you want to
// extend the snake with the piece of tail.
function addTail(aPiece:DisplayObject):void
{
// Get the last snake element.
var lastPiece:DisplayObject = Snake[Snake.length - 1];
// Sync the tail coordinates.
aPiece.x = lastPiece.x;
aPiece.y = lastPiece.y;
// Add the new piece to the snake.
Snake.push(aPiece);
}
// Add the pre-defined head as the first element.
addTail(SnakeHead);
// Now start following the Mouse.
addEventListener(Event.ENTER_FRAME, onFrame);
// Fires every frame and adjusts the whole snake, if needed.
function onFrame(e:Event):void
{
// Sync the attractor point with the Mouse.
Rat.x = mouseX;
Rat.y = mouseY;
// Now lets make each piece follow the previous piece,
// one by one, starting from the head, down to the tail.
for (var i:int = 1; i < Snake.length; i++)
{
followOne(Snake[i - 1], Snake[i]);
}
}
function followOne(A:DisplayObject, B:DisplayObject):void
{
// Think of these values as of vector
// pointing from B position to A position.
var dx:Number = A.x - B.x;
var dy:Number = A.y - B.y;
// Figure out the distance between the given pieces.
var aDist:Number = Math.sqrt(dx * dx + dy * dy);
// Do nothing if pieces are closer than 20 px apart.
// You can change this value to make snake shorter or longer.
if (aDist < 20)
{
return;
}
// This literally means "eat one tenth of the distance
// between me and the previous piece". If you want pieces
// to follow each other with more vigor, reduce this value,
// if you want the whole snake to slither smoothly, increase it.
B.x += dx / 10;
B.y += dy / 10;
// Rotate the B piece so it would look right into A's direction.
// Well, unless your pieces are round and look all the same.
B.rotation = Math.atan2(dy, dx) * 180 / Math.PI;
}

Changing size of an object in Action Script 3 gaming

I'm a beginner at Action Script 3 and currently developing a basic game of bouncing ball. The game runs perfectly with a ball bouncing and changes direction with a mouse click, as well as its color. However, now I wish to make certain changes, such as, while the game is in progress; I would want the ball's size to be tiny and as the game is being played, the ball expands. I've shared my code below, what specifically, I'm required to do at this point. Any suggestions?
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends MovieClip {
private var ball:Ball = new Ball();
private var ballSpeed, cf: int;
private var isLeft, isUp, isLand: Boolean;
public function Main() {
// constructor code
createBall();
ballSpeed = 5;
isLeft = false;
isUp = false;
isLand = true;
cf = 1;
stage.addEventListener(Event.ENTER_FRAME, frameHandler);
stage.addEventListener(MouseEvent.CLICK, changeDirection);
}
private function changeDirection(m:MouseEvent){
if(isLand){
isLand = false;
} else {
isLand = true;
}
cf += 1;
if (cf > ball.totalFrames){
cf = 1;
}
ball.gotoAndStop(cf);
}
private function createBall(){
ball.x = stage.stageWidth * .5;
ball.y = stage.stageHeight * .5;
addChild(ball);
}
private function frameHandler(e:Event){
if(isLand){
if((ball.x + ball.width * .5) < stage.stageWidth && !isLeft) {
ball.x += ballSpeed;
}
if((ball.x + ball.width * .5) >=stage.stageWidth) {
isLeft = true;
}
if((ball.x - ball.height * .5) > 0 && isLeft) {
ball.x -= ballSpeed;
}
if((ball.x - ball.width * .5) <= 0){
isLeft = false;
}
}
if(!isLand){
if((ball.y + ball.height * .5) < stage.stageHeight && !isUp){
ball.y += ballSpeed;
}
if((ball.y + ball.height * .5) >= stage.stageHeight){
isUp = true;
}
if((ball.y - ball.height * .5) > 0 && isUp){
ball.y -= ballSpeed;
}
if((ball.y - ball.width * .5) <= 0){
isUp = false;
}
}
}
}
}
You need to add a couple of lines:
private function frameHandler(e:Event):void
{
ball.scaleX += 0.01;
ball.scaleY = ball.scaleX;
So, each frame the ball will grow by 1%, so at the frame rate of 25 the ball will be twice as big in 4 seconds, trice as big in 8 seconds, and so on.

In AS3 how would i add 2 buttons that would enable the player to move on press instead of using the arrow keys?

I got this code off the internet for the game Pong to work on my AS3 document for my assignment. However i'm pretty much a beginner at code and i'm trying to get this game to work on mobile as the assignment needs a game to work on it.
Because it uses arrow keys, i would like to basically just replace them with buttons instead, one for going up and one for going down. I just don't know the type of code that would allow me to do that.
Something like, when button is pressed, player moves up or down depending which button, but im not sure where to replace the code and what to get rid of.
Here's the "Pong" class file:
package {
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
public class Pong extends MovieClip {
//constants
private var pongUp:MovieClip = new PongUp ;
private var pongDown:MovieClip = new PongDown ;
const ballspeed:int = 10;
const playerspeed:int = 7;
const computerspeed:int = 10;
const computerIntelligence:int = 7;//intelligence is 7 out of 10
//global variables
var vx:int = - ballspeed;// x component of velocity of ball (velocity is speed with direction)
var vy:int = ballspeed;// y component of velocity of ball
var v1:int = 0;// initial velocity of player
var v2:int = 0;// initial velocity of computer
var playerScore:int = 0;
var computerScore:int = 0;
var player:MovieClip = new PongPlayer ;
var computer:MovieClip = new PongComputer ;
var ball:MovieClip = new PongBall ;
public function Pong() {
//init();
addEventListener(Event.ADDED_TO_STAGE,init);
}
//this function will add all event listeners
function init(e:Event):void {
stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,KeyUp);
stage.addEventListener(Event.ENTER_FRAME,EnterFrame);
addChild(player);
addChild(computer);
addChild(ball);
player.x = 23;
player.y = 300;
computer.x = 637;
computer.y = 311;
ball.x = 308;
ball.y = 328;
addChild(pongUp);
pongUp.x = 25;
pongUp.y = 700;
addChild(pongDown);
pongDown.x = 530;
pongDown.y = 700;
}
// this function resets the game
function reset():void {
player.y = stage.stageHeight / 2;
computer.y = stage.stageHeight / 2;
ball.x = stage.stageWidth / 2;
ball.y = stage.stageHeight / 2;
if (Math.abs(Math.random() * 2) > 1)
{
vx = - ballspeed;
}
else
{
vx = ballspeed;
}
if (Math.abs(Math.random() * 2) > 1)
{
vy = - ballspeed;
}
else
{
vy = ballspeed;
}
}
//pongDown.addEventListener ( MouseEvent.MOUSE_DOWN,moveDown );
//function moveDown ( e:MouseEvent ): void
//{
//}
//this function sets the velocity of player when key is pressed
function KeyDown(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP)
{
v1 = - playerspeed;
}
else if (event.keyCode == Keyboard.DOWN)
{
v1 = playerspeed;
}
}
//this function sets the velocity of player to 0 if key is released
function KeyUp(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
v1 = 0;
}
}
//This function is executed when a frame changes
function EnterFrame(event:Event):void {
//variable decleration
var pHalfHeight = player.height / 2;// half height of player(used for collisions)
var pHalfWidth = player.width / 2;// half width of player (used for collisions)
var bHalfHeight = ball.height / 2;// half height of ball(used for collisions)
var bHalfWidth = ball.width / 2;// half width of ball (used for collisions)
//moving the player
player.y += v1;
//limiting the motion of player (it should not move beyond the stageheight)
if (player.y + pHalfHeight > stage.stageHeight)
{
player.y = stage.stageHeight - pHalfHeight;
}
else if (player.y - pHalfHeight < 0)
{
player.y = 0 + pHalfHeight;
}
//moving the ball
ball.x += vx;
ball.y += vy;
//moving the computer automatically
if (Math.abs(Math.random() * 10) < computerIntelligence)
{
var d:int = computer.y - ball.y;
if (Math.abs(d) > pHalfHeight)
{
if ((d > 0))
{
v2 = - computerspeed;
}
else
{
v2 = computerspeed;
}
}
}
computer.y += v2;
//limiting the motion of computer (it should not move beyond the stageheight)
if (computer.y + pHalfHeight > stage.stageHeight)
{
computer.y = stage.stageHeight - pHalfHeight;
}
else if (computer.y - pHalfHeight < 0)
{
computer.y = 0 + pHalfHeight;
}
//collision with horizontal walls
if (ball.y + bHalfHeight >= stage.stageHeight || ball.y - bHalfHeight <= 0)
{
vy *= -1;
}
//collision with player and computer
if (ball.x - bHalfWidth <= player.x + pHalfWidth)
{
if (Math.abs(ball.y - player.y) <= pHalfHeight)
{
vx = ballspeed;
if ((v1 != 0))
{
vy = 2 * v1;
}
}
}
else if (ball.x + bHalfWidth >= computer.x - pHalfWidth)
{
if (Math.abs(ball.y - computer.y) <= pHalfHeight)
{
vx = - ballspeed;
if ((v2 != 0))
{
vy = v2;
}
}
}
//collision with vertical walls & updating scores
if (ball.x + bHalfWidth >= stage.stageWidth)
{
playerScore += 1;
reset();
}
else if (ball.x - bHalfWidth <= 0)
{
computerScore += 1;
reset();
}
//display the score on the textfield
//txtPlayer.text = String(playerScore);
//txtComputer.text = String(computerScore);
}
}
}
For mobile, you'll want to compile using AIR for Android or iOS. You can then replace:
//this function sets the velocity of player when key is pressed
function KeyDown(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP)
{
v1 = - playerspeed;
}
else if (event.keyCode == Keyboard.DOWN)
{
v1 = playerspeed;
}
}
//this function sets the velocity of player to 0 if key is released
function KeyUp(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
v1 = 0;
}
}
with:
function KeyDown(event:TouchEvent):void {
if (event.stageY < player.y){
v1 = - playerspeed;
}else if (event.stageY > player.y){
v1 = playerspeed;
}
}
function KeyUp(event:TouchEvent):void {
v1 = 0;
}
Then replace:
//this function will add all event listeners
function init(e:Event):void {
stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,KeyUp);
with:
//this function will add all event listeners
function init(e:Event):void {
stage.addEventListener(TouchEvent.TOUCH_BEGIN, KeyDown);
stage.addEventListener(TouchEvent.TOUCH_END, KeyUp);
And make sure to use TouchEvent instead of KeyboardEvent by replacing:
import flash.events.KeyboardEvent;
with:
import flash.events.TouchEvent;
Now when you hold your finger down on the screen, the "player" will move towards that Y location. If your game is using the X axis, just change the Ys to Xs!
Hope this helps!

Adobe Flash Game Programming

I'm programming a ball game in Adobe Flash, Javascript 3 and I getting a error at line 113( the last line ) that says:
1087: Syntax error: extra characters found after end of program.
package
{
import flash.display.MovieClip
import flash.text.TextField
import flash.events.Event
import flash.events.MouseEvent
public class DocumentMain extends MovieClip
{
public const GRAVITY:Number = 2;
public const BOUNCE_FACTOR:Number = 0.8;
public var _bounces:TextField;
public var _highscore:TextField;
public var _ball:Ball;
private var _vx:Number;
private var _vy:Number;
public function DocumentMain():void
{
_vx = 10;
_vy = 0;
_ball.buttonMode = true;
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
}
private function enterFrameHandler(e:Event):void
{
// gravitate the ball
_vy += GRAVITY;
// move the ball
_ball.x += _vx;
_ball.y += _vy;
// check boundaries for collusion
checkBoundaryCollisions();
}
private function mouseDownHandler(e:MouseEvent):void
{
//hit the ball if it has been clicked
if (e.target == _ball)
{
hit(e.target.mouseX, e.target.mouseY);
}
}
private function checkBoundaryCollisions():void
{
var left:Number;
var right:Number;
var bottom:Number;
var top:Number;
left = _ball.x - (_ball.width / 2);
right = _ball.x + (_ball.width / 2);
bottom = _ball.y + (_ball.height / 2);
top = _ball.y - (_ball.height / 2);
if (left < 0 && _vx < 0)
{
_ball.x = _ball.width / 2;
_vx *= -1;
}
else if (right > stage.stageWidth && _vx > 0)
{
_ball.x = stage.stageWidth - (_ball.width / 2);
_vx *= -1;
}
if (top < 0 && _vy < 0)
{
_ball.y = _ball.height / 2;
_vy *= -1;
}
else if (bottom > stage.stageHeight && _vy > 0)
{
_ball.y = stage.stageHeight - (_ball.height / 2);
_vy *= -BOUNCE_FACTOR;
_vx *= BOUNCE_FACTOR;
if (Number(_bounces.text) > Number(_highscore.text))
{
_highscore.text = _bounce.text;
}
_bounces.text = "0";
}
}
private function hit(hitX:Number, hitY:Number):void
{
//increment bounces
_bounces.text = String.(Number(_bounces.text) + 1);
//adjust the vertical velocity of the ball
if (_vy > 0)
{
_vy *= -BOUNCE_FACTOR / 2 ;
}
_vy -= HIT_FORCE;
//adjust the horizontaly velocity of the ball
if (_vx * hitX > 0)
{
_vx *= -BOUNCE_FACTOR;
}
_vx -= ( 2 * hitX / _ball.width) * HIT_FORCE;
}
}
}
}
get rid of the last curly brace }. You have too many at the end of the file.
I also think you mean Actionscript 3.

Flash - using multiple event handlers?

so I'm working on a game which uses multiple .as files - and I'm trying to program the game however it keeps kicking back the following error when it reaches line 21 in theGame.as - the error is...
TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/addChild()
at theGame()[M:\Users\----\Documents\Programming For Fun\Flash\Tutorial - Menu System\theGame.as:21]
at main/changeState()[M:\Users\----\Documents\Programming For Fun\Flash\Tutorial - Menu System\main.as:23]
at mainMenu/brnP_Button()[M:\Users\----\Documents\Programming For Fun\Flash\Tutorial - Menu System\mainMenu.as:40]
Cannot display source code at this location.
I'm using the following .as files.
main.as
//main.as
package
{
import flash.display.*;
import flash.system.fscommand;
public class main extends MovieClip
{
public function main()
{
changeState(null, "menu");
}
public function changeState (currentState, nextState)
{
if (currentState != null)
{
removeChild(currentState);
}
switch(nextState)
{
case "menu": var mm:mainMenu = new mainMenu(changeState);
addChild(mm);
break;
case "game": var g:theGame = new theGame(changeState);
addChild(g);
break;
case "exit": fscommand("quit");
break;
}
}
}
}
mainMenu.as
`
//mainMenu.as
package
{
import flash.display.*;
import flash.events.*;
public class mainMenu extends MovieClip
{
var theCallBackFunction:Function;
private var ballX:Number = 10; // Declaring a variable known as ballX
private var ballY:Number = 0; // Declaring a variable knwon as ballY
private const GRAVITY:Number = 2; // Declaring a const variable known as gravity
public const ROTATION:Number = 1;
public const BOUNCE:Number = 0.9;
var gameBall:Ball = new Ball();
public function mainMenu(callBack)
{
addEventListener(Event.ENTER_FRAME, menuFrameHandler);
addChild(gameBall);
var btnPlay:mmPlay = new mmPlay();
btnPlay.addEventListener(MouseEvent.MOUSE_DOWN, brnP_Button);
btnPlay.x = width/2;
btnPlay.y = height/2 - btnPlay.height/2;
addChild(btnPlay);
var btnExit:mmExit = new mmExit();
btnExit.addEventListener(MouseEvent.MOUSE_DOWN, brnE_Button);
btnExit.x = width/2;
btnExit.y = height/2 - btnExit.height/2;
btnExit.y += btnExit.height + 4;
addChild(btnExit);
theCallBackFunction = callBack;
}
public function brnP_Button(e:MouseEvent)
{
removeEventListener(Event.ENTER_FRAME, menuFrameHandler);
theCallBackFunction(this, "game");
return;
}
public function brnE_Button(e:MouseEvent)
{
theCallBackFunction(this, "exit");
return;
}
private function menuFrameHandler (e:Event):void
{
// Gravitate the Ball
ballY += GRAVITY; // The ball is effected by gravity each frame
// Move The Ball
gameBall.x += ballX;
gameBall.y += ballY;
gameBall.rotation += ROTATION * ballX;
checkBoundaryCollision();
}
private function checkBoundaryCollision():void
{
var left:Number;
var right:Number;
var bottom:Number;
left = gameBall.x - (gameBall.width / 2);
right = gameBall.x + (gameBall.width / 2);
bottom = gameBall.y;
if (left < 0 && ballX < 0)
{
gameBall.x = (gameBall.width / 2)
ballX *= -1;
}
else if (right > stage.stageWidth && ballX > 0)
{
gameBall.x = stage.stageWidth - (gameBall.width / 2)
ballX *= -1;
}
else if (bottom > stage.stageHeight && ballY > 0)
{
gameBall.y = stage.stageHeight - (gameBall.height/2)
ballY *= -BOUNCE;
}
}
}
}
theGame.as
//theGame.as
package
{
import flash.display.MovieClip
import flash.text.TextField
import flash.events.Event
import flash.events.MouseEvent
public class theGame extends MovieClip
{
public const GRAVITY:Number = 2; // Declaring a const variable known as gravity
public const BOUNCE:Number = 0.8;
public const HIT:Number = 15;
public const ROTATION:Number = 1;
public var gameBall:Ball;
private var ballX:Number; // Declaring a variable known as ballX
private var ballY:Number; // Declaring a variable knwon as ballY
public function theGame(callBack): void
{
addChild(gameBall);
ballX = Math.random(); // Initalising ballX
ballY = Math.random(); // Initalising ballY
gameBall.buttonMode = true;
addEventListener(Event.ENTER_FRAME, gameFrameHandler);
addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
}
private function gameFrameHandler (e:Event):void
{
// Gravitate the Ball
ballY += GRAVITY; // The ball is effected by gravity each frame
// Move The Ball
gameBall.x += ballX;
gameBall.y += ballY;
gameBall.rotation += ROTATION * ballX;
// Check Stage Boundaries For Collisions
checkBoundaryCollision();
}
private function mouseDownHandler (e:MouseEvent):void
{
// Hit the ball if it has been clicked
if (e.target == gameBall)
{
hit(e.target.mouseX, e.target.mouseY);
}
}
private function checkBoundaryCollision():void
{
var left:Number;
var right:Number;
var bottom:Number;
var top:Number;
left = gameBall.x - (gameBall.width / 2);
right = gameBall.x + (gameBall.width / 2);
bottom = gameBall.y + (gameBall.height / 2);
top = gameBall.y - (gameBall.height / 2);
if (left < 0 && ballX < 0)
{
gameBall.x = (gameBall.width / 2)
ballX *= -1;
}
else if (right > stage.stageWidth && ballX > 0)
{
gameBall.x = stage.stageWidth - (gameBall.width / 2)
ballX *= -1;
}
if (top < 42.70 && ballY < 0)
{
gameBall.y = 42.70 + (gameBall.height / 2)
ballY *= -1;
}
else if (bottom > stage.stageHeight && ballY >= 0)
{
gameBall.y = stage.stageHeight - (gameBall.height/2)
ballY *= -BOUNCE;
ballX *= BOUNCE;
}
}
private function hit(hitX:Number, hitY:Number):void
{
// Adjust vertical velocity
if (ballY > 0)
{
ballY *= -BOUNCE / 2;
}
ballY -= HIT;
//adjust horizontal veloity
if (ballX * hitX > 0)
{
ballX *= -BOUNCE;
}
ballX -= (hitX / gameBall.width * HIT);
}
}
}
How would I go about fixing this?
You don't have an instance of gameBall inside your class theGame.
Try adding
gameBall = new Ball();
before
addChild(gameBall);