Actionscript 3.0 - MouseEvents not working - actionscript-3

I'm trying to code a sort of strategy game through FlashDevelop and I'm getting problems when trying to use Events (particularly MouseEvents). It's not so much that the events are returning errors, it's just that they don't do anything, not even getting a trace.
I'm trying to make the hexagons HexObject image invisible when clicked on (just a simple test to see if the MouseEvent is actually working).
This is my code:
Main.as
package {
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
/**
* ...
* #author Dean Sinclair
*/
public class Main extends Sprite {
public var gameInitialised:Boolean = false;
public var MIN_X:int = 0;
public var MAX_X:int = stage.stageWidth;
public var MIN_Y:int = 0;
public var MAX_Y:int = stage.stageHeight - 100;
public var GameGrid:HexGrid = new HexGrid(MIN_X, MAX_X, MIN_Y, MAX_Y);
public var blackBG:Shape = new Shape();
public function Main():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
addEventListener(Event.ENTER_FRAME, update);
// entry point
}
private function update(event:Event):void {
if (gameInitialised == false) {
GameGrid.initialiseGrid();
initialiseBackground();
gameInitialised = true;
}
updateGraphics();
}
public function drawGrid():void {
for (var x:int = 0; x < GameGrid.TOTAL_X; x++) {
for (var y:int = GameGrid.yArray[x][0]; y < GameGrid.yArray[x][1]; y++) {
if (x != GameGrid.nox || y != GameGrid.noy) {
GameGrid.Grid[x][y].update();
this.stage.addChild(GameGrid.Grid[x][y].image);
}
}
}
}
public function updateGraphics():void {
this.stage.addChild(blackBG);
drawGrid();
}
public function initialiseBackground():void {
blackBG.graphics.beginFill(0x000000, 1);
blackBG.graphics.lineStyle(10, 0xffffff, 1);
blackBG.graphics.drawRect(0, 0, stage.stageWidth-1, stage.stageHeight-1);
blackBG.graphics.endFill();
}
}
}
HexGrid.as
package {
import flash.display.Sprite;
import flash.events.Event;
/**
* ...
* #author Dean Sinclair
*/
public class HexGrid extends Sprite {
public static var HEX_RADIUS:int = 0;
public static var HEX_DIAMETER:int = 0;
public static var GRID_WIDTH:int = 0;
public static var GRID_HEIGHT:int = 0;
public var TOTAL_X:int = 0;
public var MIN_X:int = 0;
public var MAX_X:int = 0;
public var MIN_Y:int = 0;
public var MAX_Y:int = 0;
public var Grid:Array;
public var yArray:Array;
public function HexGrid(min_x:int, max_x:int, min_y:int, max_y:int) {
super();
MIN_X = min_x;
MAX_X = max_x;
MIN_Y = min_y;
MAX_Y = max_y;
}
public function initialiseGrid():void {
setGridDetails();
setLineLengths();
setGridPositions();
}
public function setGridDetails():void {
HEX_RADIUS = 25;
HEX_DIAMETER = 2 * HEX_RADIUS;
GRID_WIDTH = (((MAX_X - MIN_X) / HEX_DIAMETER) - 1);
GRID_HEIGHT = ((((MAX_Y - 100) - MIN_Y) / (HEX_DIAMETER - (HEX_DIAMETER / 3))) - 3);
TOTAL_X = GRID_WIDTH + Math.floor((GRID_HEIGHT - 1) / 2);
}
private function setLineLengths():void {
yArray = new Array(TOTAL_X);
for (var a:int = 0; a < TOTAL_X; a++) {
yArray[a] = new Array(2);
}
for (var x:int = 0; x < TOTAL_X; x++) {
if (x < GRID_WIDTH) {
yArray[x][0] = 0;
}else {
yArray[x][0] = (x - GRID_WIDTH + 1) * 2;
}
yArray[x][1] = 1 + (2 * x);
if (yArray[x][1] > GRID_HEIGHT) {
yArray[x][1] = GRID_HEIGHT;
}
trace("Line", x, " starts at", yArray[x][0], " ends at", yArray[x][1]);
}
}
public var nox:int = 5;
public var noy:int = 3;
private function setGridPositions():void {
var hexState:int = 4;
Grid = new Array(TOTAL_X);
for (var x:int = 0; x < TOTAL_X; x++) {
Grid[x] = new Array(yArray[x][1]);
for (var y:int = yArray[x][0]; y < yArray[x][1]; y++) {
if(nox!=4 || noy!=6){
Grid[x][y] = new HexObject(HEX_DIAMETER + (HEX_DIAMETER * x) - (HEX_RADIUS * y), HEX_DIAMETER + (HEX_DIAMETER * y) - ((HEX_DIAMETER / 3) * y), HEX_RADIUS, 2);
}
}
}
}
}
}
HexObject.as
package {
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
/**
* ...
* #author Dean Sinclair
*/
public class HexObject extends Sprite {
[Embed(source = "../images/hexagons/hex_darkRed.png")]
private var DarkRedHex:Class;
[Embed(source = "../images/hexagons/hex_lightBlue.png")]
private var LightBlueHex:Class;
[Embed(source = "../images/hexagons/hex_midGreen.png")]
private var MidGreenHex:Class;
public var image:Bitmap = new LightBlueHex();
protected var state:int = 0;
private var radius:int = 0;
public function HexObject(xPos:int, yPos:int, hexRadius:int, hexState:int) {
super();
x = xPos;
y = yPos;
state = hexState;
radius = hexRadius;
checkState();
initialiseGraphics();
}
private function checkState():void {
switch(state) {
case 1: // plains
image = new MidGreenHex();
break;
case 2: // hills
break;
case 3: // rock
image = new DarkRedHex();
break;
case 4: // water
image = new LightBlueHex();
break;
default:
break;
}
}
private function initialiseGraphics():void {
image.visible = true;
image.width = radius * 2;
image.height = radius * 2;
image.x = x - radius;
image.y = y - radius;
}
private function onMouseClick(e:MouseEvent):void {
image.visible = false;
trace("image.visible =", image.visible);
}
public function update():void {
image.addEventListener(MouseEvent.CLICK, onMouseClick);
}
}
}
I've tried countless methods to get the events working, but none have had any success. Any sort of solution to this would be a lifesaver as I've been toiling over this for hours, thanks!

My problem was fixed by VBCPP, I was using the class Bitmap which cannot dispatch MouseEvents. The solution was to take image from HexObject and put it inside an container of type Sprite, with the logical one being the object it was in. I just had to add the following code inside HexObject.as:
this.addChild(image);
and then just refer to the Object in future as opposed to image.

Related

State Machine Cant get to work

Learning to code so this might sound noobish...
Using Action Script
I am trying to make my Agents react to my segments so they run away.
So I need to connect part of my Main code to my Agent code
Here is my code :
Main.as
package
{
import agent.Agent;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.geom.Point;
import flash.display.Stage;
public class Main extends Sprite
{
private var score:Score;
private var count:int;
private var bleh: int = 0;
private var Agents:Vector.<Agent>;
private var segments:Array;
private var numSegments:uint = 20;
private var player:Point = new Point (200, 200)
private var friend:Agent = new Agent;
private var snakeHead:SnakeHead;
private var snakeTail:SnakeTail;
private var background: Sprite;
private var border: Bushes;
private var xVel: Number;
private var yVel: Number;
public function Main():void
{
xVel = 0;
yVel = 0;
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
snakeHead = new SnakeHead();
snakeTail = new SnakeTail();
score = new Score();
border = new Bushes;
score.x = 11;
score.y = 14;
addChild(score);
stage.addChild(border);
count = 0;
addChildAt(snakeHead,0);
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
segments = new Array();
for(var i:uint = 0; i < numSegments; i++)
{
var segment:Segment = new Segment (10, 20);
addChildAt(segment,0);
addChildAt(snakeTail,0);
segments.push(segment);
}
//updatePoint();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
removeEventListener(Event.ADDED_TO_STAGE, init);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
// entry point
background = new LevelOne(); //creates the background
addChildAt(background,0);
Agents = new Vector.<Agent>();
addEventListener(Event.ENTER_FRAME, gameloop);
for (var x:int = 0; x < 3; x++)
{
var a:Agent = new Agent();
addChild(a);
Agents.push(a);
a.x = 400;
a.y = 300;
a.name = "Name"+x;
trace (x);
}
stage.addEventListener(MouseEvent.CLICK, createAgent);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
}
private function createAgent(e:MouseEvent):void
{
var a:Agent = new Agent();
addChild(a);
Agents.push(a);
a.x = mouseX;
a.y = mouseY;
}
private function gameloop(evt:Event):void
{
for (var i:int = 0; i < Agents.length; i++)
{
Agents[i].update();
if (snakeHead.hitTestObject(Agents[i]))
{
//trace (Agents[i].name);
removeAgent(Agents[i]);
Agents.splice(i,1);
count ++;
score.lowercasetext.text = count.toString();
trace("count: " + count);
}
}
}
private function onEnterFrame(evt:Event):void
{
player.x += xVel;
player.y += yVel;
drag(snakeHead, player.x, player.y);
drag(segments[0], snakeHead.x, snakeHead.y);
for(var i:uint = 1; i < numSegments; i++)
{
var segmentA:Segment = segments[i];
var segmentB:Segment = segments[i - 1];
drag(segmentA, segmentB.x, segmentB.y);
var PlayerHalfWidth: Number = segments[i].width / 2;
var PlayerHalfHeight: Number = segments[i].height / 2;
if (segments[i].x + PlayerHalfWidth > stage.stageWidth) {
segments[i].x = stage.stageWidth - PlayerHalfWidth;
} else if (segments[i].x - PlayerHalfWidth < 0) {
segments[i].x = 0 + PlayerHalfWidth;
}
if (segments[i].y + PlayerHalfHeight > stage.stageHeight) {
segments[i].y = stage.stageHeight - PlayerHalfHeight;
}else if (segments[i].y - PlayerHalfHeight < 0) {
segments[i].y = 0 + PlayerHalfHeight;
}
var playerHalfWidth: Number = segments[i - 1].width / 2;
var playerHalfHeight: Number = segments[i - 1].height / 2;
if (segments[i - 1].x + playerHalfWidth > stage.stageWidth) {
segments[i - 1].x = stage.stageWidth - playerHalfWidth;
} else if (segments[i - 1].x - playerHalfWidth < 0) {
segments[i - 1].x = 0 + playerHalfWidth;
}
if (segments[i - 1].y + playerHalfHeight > stage.stageHeight) {
segments[i - 1].y = stage.stageHeight - playerHalfHeight;
}else if (segments[i - 1].y - playerHalfHeight < 0) {
segments[i - 1].y = 0 + playerHalfHeight;
}
}
drag(snakeTail, segments[19].x, segments[19].y);
var HeadHalfWidth: Number = snakeHead.width / 2;
var HeadHalfHeight: Number = snakeHead.height / 2;
if (snakeHead.x + HeadHalfWidth > stage.stageWidth) {
snakeHead.x = stage.stageWidth - HeadHalfWidth;
} else if (snakeHead.x - HeadHalfWidth < 0) {
snakeHead.x = 0 + HeadHalfWidth;
}
if (snakeHead.y + HeadHalfHeight > stage.stageHeight) {
snakeHead.y = stage.stageHeight - HeadHalfHeight;
}else if (snakeHead.y - HeadHalfHeight < 0) {
snakeHead.y = 0 + HeadHalfHeight;
}
//drag(segments[19], snakeTail.x, snakeTail.y);
/*for each (var a: Agent in Agents) {
a.update();
trace ("Follow me on Twitter.");
if(segments[0].hitTestObject(a))
{
trace("True");
trace(bleh + " " + "F*CKING HELL!");
trace(a.name);
stage.removeChild(Agents[1]);
}
}*/
}
private function removeAgent(a:Agent):void
{
a.parent.removeChild(a);
trace("Collision Detected!");
}
private function keyDown (evt: KeyboardEvent): void {
//87=w 68=d 83=s 65=a
if (evt.keyCode == 87)
{
player;
yVel = -5;
}
if (evt.keyCode == 83)
{
player;
yVel = 5;
}
if (evt.keyCode == 68)
{
player;
xVel = 5;
}
if (evt.keyCode == 65)
{
player;
xVel = -5;
}
//trace (player.x + " " + player.y);
trace (xVel + " " + yVel);
}
private function keyUp (evt: KeyboardEvent): void {
//87=w 68=d 83=s 65=a
if (evt.keyCode == 87)
{
player;
yVel = 0;
}
else if (evt.keyCode == 83)
{
player;
yVel = 0;
}
else if (evt.keyCode == 68)
{
player;
xVel = 0;
}
else if (evt.keyCode == 65)
{
player;
xVel = 0;
}
}
private function drag(segment:MovieClip, xpos:Number, ypos:Number):void
{
var dx:Number = xpos - segment.x;
var dy:Number = ypos - segment.y;
var angle:Number = Math.atan2(dy, dx);
segment.rotation = angle * 180 / Math.PI;
var w:Number = segment.getPin().x - segment.x;
var h:Number = segment.getPin().y - segment.y;
segment.x = xpos - w;
segment.y = ypos - h;
}
}
}
Agent.as
package agent
{
import agent.states.ChaseState;
import agent.states.ConfusionState;
import agent.states.FleeState;
import agent.states.IAgentState;
import agent.states.IdleState;
import agent.states.WanderState;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.geom.Point;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.display.MovieClip;
import flash.events.*;
import Segment;
import Main;
public class Agent extends MovieClip
{
private var mouses:mouse;
public static const IDLE:IAgentState = new IdleState(); //Define possible states as static constants
public static const WANDER:IAgentState = new WanderState();
public static const CHASE:IAgentState = new ChaseState();
public static const FLEE:IAgentState = new FleeState();
public static const CONFUSED:IAgentState = new ConfusionState();
public var snake:Segment;
private const RAD_DEG:Number = 180 / Math.PI;
private var _previousState:IAgentState; //The previous executing state
private var _currentState:IAgentState; //The currently executing state
private var _pointer:Shape;
private var _tf:TextField;
public var velocity:Point = new Point();
public var speed:Number = 0;
public var fleeRadius:Number = 100; //If the mouse is "seen" within this radius, we want to flee
public var chaseRadius:Number = 50; //If the mouse is "seen" within this radius, we want to chase
public var numCycles:int = 0; //Number of updates that have executed for the current state. Timing utility.
public function Agent()
{
//Boring stuff here
_tf = new TextField();
_tf.defaultTextFormat = new TextFormat("_sans", 10);
_tf.autoSize = TextFieldAutoSize.LEFT;
_pointer = new Shape();
mouses = new mouse();
snake = new Segment(1, 1);
/*g.beginFill(0);
g.drawCircle(0, 0, 5);
g.endFill();
g.moveTo(0, -5);
g.beginFill(0);
g.lineTo(10, 0);
g.lineTo(0, 5);
g.endFill();*/
addChild(mouses);
addChild(_tf);
_currentState = IDLE; //Set the initial state
}
/**
* Outputs a line of text above the agent's head
* #param str
*/
public function say(str:String):void {
_tf.text = str;
_tf.y = -_tf.height - 2;
}
/**
* Trig utility methods
*/
public function get canSeeMouse():Boolean {
var dot:Number = snake.x * velocity.x + snake.y * velocity.y;
return dot > 0;
}
public function get distanceToMouse():Number {
var dx:Number = x - snake.x;
var dy:Number = y - snake.y;
return Math.sqrt(dx * dx + dy * dy);
}
public function randomDirection():void {
var a:Number = Math.random() * 6.28;
velocity.x = Math.cos(a);
velocity.y = Math.sin(a);
}
public function faceMouse(multiplier:Number = 1):void {
var dx:Number = snake.x - x;
var dy:Number = snake.y - y;
var rad:Number = Math.atan2(dy, dx);
velocity.x = multiplier*Math.cos(rad);
velocity.y = multiplier*Math.sin(rad);
}
/**
* Update the current state, then update the graphics
*/
public function update():void {
if (!_currentState) return; //If there's no behavior, we do nothing
numCycles++;
_currentState.update(this);
x += velocity.x*speed;
y += velocity.y*speed;
if (x + velocity.x > stage.stageWidth || x + velocity.x < 0) {
x = Math.max(0, Math.min(stage.stageWidth, x));
velocity.x *= -1;
}
if (y + velocity.y > stage.stageHeight || y + velocity.y < 0) {
y = Math.max(0, Math.min(stage.stageHeight, y));
velocity.y *= -1;
}
mouses.rotation = RAD_DEG * Math.atan2(velocity.y, velocity.x);
}
public function setState(newState:IAgentState):void {
if (_currentState == newState) return;
if (_currentState) {
_currentState.exit(this);
}
_previousState = _currentState;
_currentState = newState;
_currentState.enter(this);
numCycles = 0;
}
public function get previousState():IAgentState { return _previousState; }
public function get currentState():IAgentState { return _currentState; }
}
}

Flash, AS3: Dynamic MovieClips won't show if link them to as3 custom class

I'm writing a little flash game, and i have faced a problem adding MovieClips to stage.
I have function createBricks(), which is adding MovieClips to stage. If i do it like this:
public function createBricks():void
{
for (var i:int = 0; i < amountOfBricks; i++)
{
var brick:MovieClip = new brick2();
brick.x = i * brick.width + 10;
brick.y = 6;
addChild(brick);
}
}
Everything is okay, i can see bricks on stage. But the problem is I need to have some logic in Brick class.
So if I do it like this:
public function createBricks():void
{
for (var i:int = 0; i < amountOfBricks; i++)
{
var brick:MovieClip = new Brick(this);
brick.x = i * brick.width + 10;
brick.y = 6;
addChild(brick);
}
}
I can't see MovieClips on stage.
Any help is appreciated.
class Brick code:
package
{
import flash.display.MovieClip;
import flash.events.Event;
import Arkanoid;
public class Brick extends MovieClip
{
private var mParent:MovieClip;
public function Brick(parent:Arkanoid)
{
this.mParent = parent;
super();
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
private function enterFrameHandler(event:Event):void
{
if (this.hitTestObject(mParent.view.ball))
{
mParent.ballYSpeed *= -1;
mParent.removeChild(this);
removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
}
}
}
game class:
package
{
import flash.display.MovieClip;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.MouseEvent
import flash.events.Event;
import Brick;
public class Arkanoid extends MovieClip
{
private var mView:MovieClip;
private var paddle:MovieClip;
private var ball:MovieClip;
private var amountOfBricks:int = 6;
private var ballXSpeed:int = 10;
private var ballYSpeed:int = 10;
public function Arkanoid()
{
mView = new GameView();
paddle = mView.paddle;
ball = mView.ball;
super();
}
public function start():void
{
addListeners();
paddle.x = 100;
createBricks();
addChild(mView);
}
public function addListeners():void
{
mView.addEventListener(MouseEvent.MOUSE_MOVE, paddle_mouseMoveHandler);
mView.addEventListener(Event.ENTER_FRAME, ball_enterFrameHandler);
}
private function paddle_mouseMoveHandler(event:MouseEvent):void
{
paddle.x = mouseX - paddle.width / 2;
if (mouseX < paddle.width / 2)
{
paddle.x = 0;
}
if (mouseX > mView.width - paddle.width / 2)
{
paddle.x = mView.width - paddle.width;
}
}
private function ball_enterFrameHandler(event:Event):void
{
ball.x += ballXSpeed;
ball.y += ballYSpeed;
if (ball.x >= mView.width - ball.width)
{
ballXSpeed *= -1;
}
if (ball.x <= 0)
{
ballXSpeed *= -1;
}
if (ball.y >= mView.height - ball.height)
{
ballYSpeed *= -1;
}
if (ball.y <= 0)
{
ballYSpeed *= -1;
}
if (ball.hitTestObject(paddle))
{
calculateBallAngle();
}
}
private function calculateBallAngle():void
{
var ballPosition:Number = ball.x - paddle.x;
var hitPercent:Number = (ballPosition / (paddle.width - ball.width)) - .5;
ballXSpeed = hitPercent * 10;
ballYSpeed = - 1;
}
public function createBricks():void
{
for (var i:int = 0; i < amountOfBricks; i++)
{
//var brick:MovieClip = new brick2();
var brick:MovieClip = new Brick(this);
brick.x = i * brick.width + 10;
brick.y = 6;
addChild(brick);
}
}
public function get view():MovieClip
{
return mView;
}
}
}
1| Create class called Brick
class Brick extends MovieClip {
var ground;
public function Brick(_ground){
ground = _ground;
var brickSample:MovieClip = new brick2();
addChild(brickSample);
}
}
2| Now you can create your movieclips like you want
public function createBricks():void
{
for (var i:int = 0; i < amountOfBricks; i++)
{
var brick:MovieClip = new Brick(this);
brick.x = i * brick.width + 10;
brick.y = 6
addChild(brick);
}
}
hope it helps

Moving b2body With Keyboard

I have this code that gives the b2Body an impulse towards the cursor when you click on stage.
private function clicked(e:MouseEvent):void
{
var impulse_x:Number = (mouseX / world_scale - mainChar.GetPosition().x);
var impulse_y:Number = (mouseY / world_scale - mainChar.GetPosition().y);
var impulse:b2Vec2 = new b2Vec2(impulse_x, impulse_y);
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
}
I was trying to use keyboard right arrow key for movement and so in the update function I added the if key[Keyboard.RIGHT]:
private function update(e:Event):void {
world.Step (1 / 30, 10, 10);
if (key[Keyboard.RIGHT]) {
impulse_x = 3;
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
}
}
private function onKeyUp(e:KeyboardEvent):void
{
key[e.keyCode] = false;
}
private function onKeyDown(e:KeyboardEvent):void
{
key[e.keyCode] = true;
}
But the b2body goes to top left on the screen and stays there and doesn't move. I am changing the impulse value that then goes into the vector that is applied to the body.
Although it doesn't give me any errors.
EDIT: The whole code!
package
{
import Box2D.Collision.Shapes.b2PolygonShape;
import Box2D.Common.Math.b2Vec2;
import Box2D.Dynamics.b2Body;
import Box2D.Dynamics.b2BodyDef;
import Box2D.Dynamics.b2FixtureDef;
import Box2D.Dynamics.b2World;
import Box2D.Dynamics.Contacts.b2ContactEdge;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
public class Main extends Sprite
{
public var world:b2World = new b2World(new b2Vec2(0, 0), true);
public var world_scale:Number = 30;
public var mainChar:b2Body;
private var ground:b2Body;
public var keys:Array = [];
public var beingPressed:Boolean;
public var impulse_x:Number;
public var impulse_y:Number;
public var impulse:b2Vec2 = new b2Vec2(impulse_x, impulse_y);
public function Main():void
{
createMainCharacter(stage.stageWidth / 2, stage.stageHeight / 2, 50, 100);
var th:uint = 10;
addEventListener(Event.ENTER_FRAME, update);
//stage.addEventListener(MouseEvent.CLICK, clicked);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
/**private function clicked(e:MouseEvent):void
{
var impulse_x:Number = (mouseX / world_scale - mainChar.GetPosition().x);
var impulse_y:Number = (mouseY / world_scale - mainChar.GetPosition().y);
var impulse:b2Vec2 = new b2Vec2(impulse_x, impulse_y);
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
}**/
private function update(e:Event):void
{
world.Step (1 / 30, 10, 10);
var temp:Sprite;
for (var body:b2Body = world.GetBodyList(); body != null; body = body.GetNext())
{
if (body.GetUserData())
{
temp = body.GetUserData() as Sprite;
temp.x = body.GetPosition().x * world_scale;
temp.y = body.GetPosition().y * world_scale;
temp.rotation = body.GetAngle() * (180 / Math.PI); // radians to degrees
}
}
if (keys[Keyboard.RIGHT])
{
impulse_x = 3;
impulse_y = 0;
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
} else {
impulse_x = 0;
impulse_y = 0;
}
}
private function createMainCharacter(x:Number, y:Number, width:Number, height:Number):void
{
var mainCharSprite:Sprite = new Sprite();
mainCharSprite.graphics.beginFill(0x000000);
mainCharSprite.graphics.drawRect( -width / 2, -height / 2 , width, height);
mainCharSprite.graphics.endFill;
mainCharSprite.x = x;
mainCharSprite.y = y;
addChild(mainCharSprite);
var mainCharDef:b2BodyDef = new b2BodyDef();
mainCharDef.userData = mainCharSprite;
mainCharDef.type = b2Body.b2_dynamicBody;
mainCharDef.position.Set (x / world_scale, y / world_scale);
mainChar = world.CreateBody(mainCharDef);
var shape:b2PolygonShape = new b2PolygonShape();
shape.SetAsBox((width / 2) / world_scale, (height / 2) / world_scale);
var fixtureDef:b2FixtureDef = new b2FixtureDef();
fixtureDef.shape = shape;
fixtureDef.restitution = 0.1;
fixtureDef.friction = 0.1;
fixtureDef.density = 0.5;
mainChar.CreateFixture(fixtureDef);
}
private function onKeyUp(e:KeyboardEvent):void
{
keys[e.keyCode] = false;
}
private function onKeyDown(e:KeyboardEvent):void
{
keys[e.keyCode] = true;
}
}
}
Changing the values of impulse_x and impulse_y is not going to update the values used by the b2Vec2 impulse. In AS3 primitives are passed by value not by reference. If you want the b2Vec2 object referenced by the variable impulse to change its values you need to change them directly on the object itself:
impulse.x = 3.0;
impulse.y = 0.0;
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());

All my references to the stage method are throwing null reference errors in as3

I'm not sure what the change was that caused this, but suddenly i'm getting null object references in all the cases that I use the stage method as a parameter. My code is too long to fit all the different instances, so I'll just attach one or two.
package com.Mass.basics1
{
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
public class Main extends MovieClip
{
public var ourPlanet:Cosmo = new Cosmo(stage);
public var ourAsteroid:Asteroid = new Asteroid();
private var numStars:int = 80;
private var numAsteroids:int = 5;
public static var a:Number = 0;
private var stageRef:Stage;
//public var ourAsteroid:Asteroid = new Asteroid(stage);
//private var ourAsteroid:Asteroid = new Asteroid();
//our constructor function. This runs when an object of
//the class is created
public function Main()
{
//create an object of our ship from the Ship class
stop();
//add it to the display list
stage.addChild(ourPlanet);
ourPlanet.x = stage.stageWidth / 2;
ourPlanet.y = stage.stageHeight / 2;
this.stageRef = stageRef;
for (var i:int = 0; i < numStars; i++)
{
stage.addChildAt(new Star(stage), stage.getChildIndex(ourPlanet));
}
for (var o:int = 0; o < numAsteroids; o++)
{
stage.addChildAt(new Asteroid(), stage.getChildIndex(ourPlanet));
}
My debugger tells me there is a null object reference at line 13, and this code is from my engine. Cosmo is another external file that is linked to a symbol. I'll post the code from there, but there are about 4 of these errors across 4 different .as files, but it'd be too much code to put in here, so I'll just add from one other file I think would be important.
Code From Cosmo.as
package com.Mass.basics1
{
import flash.display.MovieClip;
import flash.display.Stage;
import com.senocular.utils.KeyObject;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.text.TextField;
public class Cosmo extends MovieClip
{
private var stageRef:Stage;
private var key:KeyObject;
private var speed:Number = 20;
private var vx:Number = 0;
private var vy:Number = 0;
private var friction:Number = 0.93;
private var maxspeed:Number = 8;
public var destroyed:Boolean = false;
public function Cosmo(stageRef:Stage)
{
this.stageRef = stageRef;
var key:KeyObject = new KeyObject(stage);
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
public function loop(e:Event) : void
{
//keypresses
if (key.isDown(Keyboard.A))
vx -= speed;
else if (key.isDown(Keyboard.D))
vx += speed;
else
vx *= friction;
if (key.isDown(Keyboard.W))
vy -= speed;
else if (key.isDown(Keyboard.S))
vy += speed;
else
vy *= friction;
//update position
x += vx;
y += vy;
//speed adjustment
if (vx > maxspeed)
vx = maxspeed;
else if (vx < -maxspeed)
vx = -maxspeed;
if (vy > maxspeed)
vy = maxspeed;
else if (vy < -maxspeed)
vy = -maxspeed;
//ship appearance
rotation = vx;
scaleX = (maxspeed - Math.abs(vx))/(maxspeed* 4) + 0.75;
//stay inside screen
if (x > stageRef.stageWidth)
{
x = stageRef.stageWidth;
vx = -vx;
}
else if (x < 0)
{
x = 0;
vx = -vx;
}
if (y > stageRef.stageHeight)
{
y = stageRef.stageHeight;
vy = -vy;
}
else if (y < 0)
{
y = 0;
vy = -vy;
}
}
}
}
I'm also getting an error here at line 26 for the same thing.
Code from another file
package com.senocular.utils {
import flash.display.Stage;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
/**
* The KeyObject class recreates functionality of
* Key.isDown of ActionScript 1 and 2
*
* Usage:
* var key:KeyObject = new KeyObject(stage);
* if (key.isDown(key.LEFT)) { ... }
*/
dynamic public class KeyObject extends Proxy {
private static var stage:Stage;
private static var keysDown:Object;
public function KeyObject(stage:Stage) {
construct(stage);
}
public function construct(stage:Stage):void {
KeyObject.stage = stage;
keysDown = new Object();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
}
flash_proxy override function getProperty(name:*):* {
return (name in Keyboard) ? Keyboard[name] : -1;
}
public function isDown(keyCode:uint):Boolean {
return Boolean(keyCode in keysDown);
}
public function deconstruct():void {
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyReleased);
keysDown = new Object();
KeyObject.stage = null;
}
private function keyPressed(evt:KeyboardEvent):void {
keysDown[evt.keyCode] = true;
}
private function keyReleased(evt:KeyboardEvent):void {
delete keysDown[evt.keyCode];
}
}
}
In this file, i'm getting errors at lines 23 and 29. Thanks in advance, let me know if you need more information of any kind.
The stage property is going to be null until added to the display list hierarchy of the stage. You can't add the object to the stage until after the constructor is executed, so therefore you won't ever be able to access stage in the constructor. It's going to be null.
Call the construct method after creating the instance and adding it to the stage's display list hierarchy.

adding a object to another object in as3

Ok so i have a character on the screen and when it moves the camera follows(thanks to manifest222 on youtube) i have a wall where the player cant go through. I also have boxes adding to the stage but i want it so that the box adds to onto another object hers the code.
package {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.display.Stage;
public class Main extends MovieClip {
// player
public var characterEndMC:MovieClip = new charEndMC();
public var arrayOfBarrier:Array = new Array();
//box
private var boxAmount:Number=0;
private var boxLimit:Number=20;
private var _root:Object;
//$txt
public var money:int=0;
public var gold:int=0;
public var my_scrollbar:MakeScrollBar;
//$$
public var testnumber:Number=1;
//enemy1
private var e01Amount:Number=0;
private var e01Limit:Number=2;
public function Main() {
$box.click$.move$.buttonMode=true;
$box.click$.clickmini$.buttonMode=true;
backgroundpic.visible = false;
character_mc["charAngle"]=0;
character_mc["moveX"]=0;
character_mc["moveY"]=0;
character_mc["walkSpeed"]=5;
stage.addEventListener(MouseEvent.CLICK, charMove);
//box add listener
addEventListener(Event.ENTER_FRAME, eFrame);
//moneybox
$box.click$.move$.addEventListener(MouseEvent.MOUSE_DOWN, startmoving$);
$box.click$.move$.addEventListener(MouseEvent.MOUSE_UP, stopmoving$);
$box.click$.clickmini$.addEventListener(MouseEvent.CLICK, c$mini);
my_scrollbar=new MakeScrollBar(scroll_mc,scroll_text);
}
public function charLoop(event:Event) {
if (character_mc.hitTestPoint(character_mc["charEnd"].x,character_mc["charEnd"].y,true)) {
character_mc["moveX"]=0;
character_mc["moveY"]=0;
this.removeChild(character_mc["charEnd"]);
character_mc.removeEventListener(Event.ENTER_FRAME, charLoop);
}
for (var j:int = 0; j < arrayOfBarrier.length; j++) {
if (character_mc.hitTestObject(arrayOfBarrier[j])) {
character_mc.x-=character_mc["moveX"];
character_mc.y-=character_mc["moveY"];
character_mc["moveX"]=0;
character_mc["moveY"]=0;
this.removeChild(character_mc["charEnd"]);
character_mc.removeEventListener(Event.ENTER_FRAME, charLoop);
}
}
for (var i:int = 0; i < this.numChildren; i++) {
this.getChildAt(i).x-=character_mc["moveX"];
this.getChildAt(i).y-=character_mc["moveY"];
}
character_mc.x+=character_mc["moveX"]+.05;
character_mc.y+=character_mc["moveY"]+.05;
}
public function lookAtMouse() {
var characterMC:MovieClip=character_mc;
characterMC["charAngle"] = Math.atan2(this.mouseY - characterMC.y, this.mouseX - characterMC.x) / (Math.PI / 180);
characterMC.rotation=characterMC["charAngle"];
}
public function charMove(event:MouseEvent) {
lookAtMouse();
this.addChild(characterEndMC);
characterEndMC.x=this.mouseX;
characterEndMC.y=this.mouseY;
character_mc["charEnd"]=characterEndMC;
character_mc["charEnd"].visible = false;
character_mc["moveX"]=Math.cos(character_mc["charAngle"]*Math.PI/180)*character_mc["walkSpeed"];
character_mc["moveY"]=Math.sin(character_mc["charAngle"]*Math.PI/180)*character_mc["walkSpeed"];
character_mc.addEventListener(Event.ENTER_FRAME, charLoop);
}
//boxadding
private function eFrame(event:Event):void {
if (boxAmount<boxLimit) {
boxAmount++;
var _box:Box=new Box ;
_box.addEventListener(MouseEvent.CLICK,boxclick);
_box.buttonMode=true;
_box.y=Math.random()* backgroundpic.height;
_box.x=Math.random()* backgroundpic.width;
addChild(_box);
}
if (e01Amount<e01Limit) {
e01Amount++;
var Enemy1: enemy01=new enemy01 ;
Enemy1.addEventListener(MouseEvent.CLICK, en01click);
Enemy1.buttonMode=true;
Enemy1.y=Math.random()*stage.stageHeight;
Enemy1.x=Math.random()*stage.stageWidth;
addChild(Enemy1);
}
}
public function boxclick(event:MouseEvent):void {
var _box:Box=event.currentTarget as Box;
logtxt.appendText("You collected " + testnumber + " boxes" + "\n" );
character_mc["moveX"] = _box.y + 40 + (character_mc.height / 2);
character_mc["moveY"]=_box.x;
logtxt.scrollV=logtxt.maxScrollV;
var randVal$:Number=Math.random();
if (randVal$>=0.49) {
money+=100;
} else if (randVal$ <= 0.50 && randVal$ >= 0.15) {
money+=200;
} else if (randVal$ <= 0.14 && randVal$ >= 0.02) {
gold+=10;
} else if (randVal$ == 0.01) {
money+=200;
gold+=20;
}
testnumber++;
boxAmount--;
$box.box$in.box$insins.Moneytxt.text=String(money);
$box.box$in.box$insins.Goldtxt.text=String(gold);
removeChild(_box);
}
private function startmoving$(event:MouseEvent):void {
$box.startDrag();
}
private function stopmoving$(event:MouseEvent):void {
$box.stopDrag();
}
private function c$mini(event:MouseEvent):void {
$box.click$.move$.visible=false;
$box.box$in.visible=false;
$box.y=200;
$box.x=100;
$box.click$.clickmini$.addEventListener(MouseEvent.CLICK, reclickbox$);
$box.click$.clickmini$.removeEventListener(MouseEvent.CLICK, c$mini);
}
private function reclickbox$(event:MouseEvent):void {
$box.click$.clickmini$.addEventListener(MouseEvent.CLICK, c$mini);
$box.click$.clickmini$.removeEventListener(MouseEvent.CLICK, reclickbox$);
$box.y=70;
$box.x=250;
$box.click$.move$.visible=true;
$box.box$in.visible=true;
}
public function scroll_text( n:Number ) {
logtxt.scrollV = Math.round( ( logtxt.maxScrollV - 1 ) * n ) + 1;
}
public function en01click (event:MouseEvent){
}
}
}
That's:
var _box:Box = new Box();
receivingDisplayObjectInstanceName.addChild(_box);