State Machine Cant get to work - actionscript-3

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; }
}
}

Related

How to implement enemy behaviour based on type?

I am building a game which create three types of enemy.Amount them only type 3 can fire others cannt.This is my enemy class
package
{
import flash.display.MovieClip;
import flash.utils.getTimer;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.geom.Point;
public class Enemy extends MovieClip
{
private var lastTime:int;
var hitCounter:Number = 1;
public var eType:Number = 0;
private var startYpos:Number = 0;
var nextFire:Timer;
var enemyType:Number;
public var bullets:Array = new Array ;
var speedY:Number = 50;
var enemySpeed:Number = 50;
var firstPos:Number = 0;
var fireCounter:Number = 0;
var firePause:Number = 10;
public function Enemy(xPos,yPos:Number,t:Number)
{
// constructor code
this.x = xPos;
firstPos = this.y = yPos;
this.enemyType = t;
lastTime = getTimer();
this.gotoAndStop(t);
addEventListener(Event.ENTER_FRAME,moveEnemy);
}
public function moveEnemy(event:Event)
{
// get time passed
var timePassed:int = getTimer() - lastTime;
lastTime += timePassed;
// move bullet
if (this.y + this.height / 2 > firstPos + 100 && speedY > 0)
{
speedY *= -1;
}
if (this.y - this.height / 2 < firstPos && speedY < 0)
{
speedY *= -1;
}
this.x -= enemySpeed * timePassed / 1000;
this.y += speedY * timePassed / 1000;
// bullet past top of screen
if (this.x - this.width / 2 < 0)
{
deleteEnemy();
}
if (this.enemyType == 3)
{
canFire();
}
}
public function canFire()
{
if ((fireCounter > firePause))
{
MovieClip(parent).createEnemyBullet();
trace((('Enemy Type : ' + enemyType) + ' and firing'));
fireCounter = 0;
}
else
{
fireCounter++;
}
}
public function deleteEnemy()
{
if (this.currentFrame == 2)
{
this.gotoAndStop(4);
}
else
{
//trace(MovieClip(parent).enemyKilled[this.enemyType-1]);
MovieClip(parent).enemyKilled[this.enemyType - 1]++;
MovieClip(parent).removeEnemy(this);
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveEnemy);
}
}
}
}
Now once a enemy type 3 start firing then every enemy start firing.i want just only enemy type 3 can fire not other enemy.How i do it?
Thanks in advance
Addition :
public function createEnemyBullet()
{
var bullet:Bullet = new Bullet(enemy.x - 10,enemy.y,500,-1);
bullets.push(bullet);
addChild(bullet);
//setEnemyBullet();
}
Then why don't you try something like this. `
public function canFire()
{
if(enemyType == 3){
return;
}
if ((fireCounter > firePause))
{
MovieClip(parent).createEnemyBullet();
trace((('Enemy Type : ' + enemyType) + ' and firing'));
fireCounter = 0;
}
else
{
fireCounter++;
}
}
`

CS6 Error 1120: Access of undefined property p1RotateTimer

all.
I'm trying to use timers within my code for ship rotation, movement, and turret rotation in a battleship-themed project that I am working on. However, Error 1120 continues to show up, despite my efforts. Any advice?
Attached is my code. The problem occurs when I do utilize TurretArray and when I do addEventListener for the timers.
package
{
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.display.DisplayObject;
import flash.events.TimerEvent;
import flash.events.*;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.*;
import flash.text.*;
import flash.utils.*;
import fl.transitions.*;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.easing.None;
import flash.display.*;
import flash.ui.*;
[SWF(width = "600", height = "480")]
public class Main extends MovieClip
{
private var game:Game = new Game();
//Sets speeds to objects
private var bulletSpeed:int = 7;
private var playerSpeed:Number = 0.4;
private var playerRotateSpeed:Number = 0.1;
//Create an array to hold multiple sprites
private var mySpriteHolder = new Array();
private var BulletAngle = new Array();
private var BulletBounce = new Array();
//Create a counter to keep track of the sprites
private var lbCounter:int = 0;
//Maximum number of sprites (count starts a 1 not 0)
private var maxLB:int = 20;
//Variable for player 1
private var player1angle:Number = 270;
private var keyPressed1:int = 0;
private var keyPressed2:int = 0;
private var keyPressed3:int = 0;
private var keyPressed4:int = 0;
private var p1Score:int = 0;
private var reloaded:int = 0;
private var k:int = 0;
private var reloadTime:int = 10;
private var TurretArray:Array = new Array();
//public function loadTurrets(){
//TurretArray = new Array();
TurretArray[0] = mvi_PTurret1; //Problem occurs in these 3 lines
TurretArray[1] = mvi_PTurret2;
TurretArray[2] = mvi_PTurret3;
//}
private var Turret1SpinDirection:int = 2;
private var Turret2SpinDirection:int = 2;
private var PTurret1angle:Number = 270;
private var PTurret2angle:Number = 270;
//create a new Timer
private var p1RotateTimer:Timer = new Timer(10);
private var p1MoveTimer:Timer = new Timer(10);
private var PTurretRotateTimer:Timer = new Timer(10);
//public function loadTimers(){
//add a listener to the timer
p1RotateTimer.addEventListener("timer",p1Rotate); //Problem here
p1MoveTimer.addEventListener("timer",p1Move);
PTurretRotateTimer.addEventListener("timer",PTurretRotate);
//}
//Create a listener for the keypress
//this.addEventListener(KeyboardEvent.KEY_DOWN,PMove);
// this.addEventListener(KeyboardEvent.KEY_UP,PStop);
// this.addEventListener(MouseEvent.MOUSE_MOVE,mouseCoordinate);
public function p1Rotate(eventArgs:TimerEvent):void{
var i:int;
if(keyPressed1 == 68){
mvi_PBattleship.rotation += playerRotateSpeed;
player1angle += playerRotateSpeed;
if(player1angle == 360){
player1angle = 0;
}
/*for(i = 0; i < 3; i++){
TurretArray[i].rotation += playerRotateSpeed;
TurretArray[i].rotation = Math.round(TurretArray[i].rotation);
}*/
//txt_PlayerAngle.text = player1angle.toString();
}
if(keyPressed2 == 65){
mvi_PBattleship.rotation -= playerRotateSpeed;
player1angle -= playerRotateSpeed;
if(player1angle == 0){
player1angle = 360;
}
/*for(i = 0; i < 3; i++){
TurretArray[i].rotation -= playerRotateSpeed;
TurretArray[i].rotation = Math.round(TurretArray[i].rotation);
}*/
//txt_PlayerAngle.text = player1angle.toString();
}
//Keeps Turret 1 with the ship
mvi_PTurret1.x = Math.cos(player1angle* (Math.PI/180)) * 32.9 + mvi_PBattleship.x;
mvi_PTurret1.y = Math.sin(player1angle* (Math.PI/180)) * 32.9 + mvi_PBattleship.y;
//Keeps Turret 2 with the ship
mvi_PTurret2.x = Math.cos(player1angle* (Math.PI/180)) * 13.4 + mvi_PBattleship.x;
mvi_PTurret2.y = Math.sin(player1angle* (Math.PI/180)) * 13.4 + mvi_PBattleship.y;
//Keeps Turret 3 with the ship
mvi_PTurret3.x = Math.cos(player1angle* (Math.PI/180)) * -56.5 + mvi_PBattleship.x;
mvi_PTurret3.y = Math.sin(player1angle* (Math.PI/180)) * -56.5 + mvi_PBattleship.y;
}
public function p1Move(eventArgs:TimerEvent):void{
/*if(p1Score > 0){
p1Score -= pointsLost;
}*/
//This moves the player forward or backwards in the correct direction
if(keyPressed3 == 87){
x -= Math.cos(player1angle* (Math.PI/180)) * playerSpeed;
y -= Math.sin(player1angle* (Math.PI/180)) * playerSpeed;
}
if(keyPressed4 == 83){
x += Math.cos(player1angle* (Math.PI/180)) * playerSpeed;
y += Math.sin(player1angle* (Math.PI/180)) * playerSpeed;
}
//This keeps the player in the center of the screen
mvi_PBattleship.x =-x + 400;
mvi_PBattleship.y =-y + 300;
//txt_PBattleshipx.text = x.toString();
//txt_PBattleshipy.text = y.toString();
//Keeps Turret 1 with the ship
mvi_PTurret1.x = Math.cos(player1angle* (Math.PI/180)) * 32.9 + mvi_PBattleship.x;
mvi_PTurret1.y = Math.sin(player1angle* (Math.PI/180)) * 32.9 + mvi_PBattleship.y;
//Keeps Turret 2 with the ship
mvi_PTurret2.x = Math.cos(player1angle* (Math.PI/180)) * 13.4 + mvi_PBattleship.x;
mvi_PTurret2.y = Math.sin(player1angle* (Math.PI/180)) * 13.4 + mvi_PBattleship.y;
//Keeps Turret 3 with the ship
mvi_PTurret3.x = Math.cos(player1angle* (Math.PI/180)) * -56.5 + mvi_PBattleship.x;
mvi_PTurret3.y = Math.sin(player1angle* (Math.PI/180)) * -56.5 + mvi_PBattleship.y;
}
public function PMove(Evt:KeyboardEvent):void{
//trace(Evt.keyCode);
if(Evt.keyCode==68){
keyPressed1 = 68;
p1RotateTimer.start();
}
if(Evt.keyCode==65){
keyPressed2 = 65;
p1RotateTimer.start();
}
if(Evt.keyCode==87){
keyPressed3 = 87;
p1MoveTimer.start();
}
if(Evt.keyCode==83){
keyPressed4 = 83;
p1MoveTimer.start();
}
}
public function PStop(Evt:KeyboardEvent):void{
if(Evt.keyCode==87){
keyPressed3 = 0;
p1MoveTimer.stop();
}
else if(Evt.keyCode==83){
keyPressed4 = 0;
p1MoveTimer.stop();
}
else if(Evt.keyCode==68){
keyPressed1 = 0;
p1RotateTimer.stop();
}
else if(Evt.keyCode==65){
keyPressed2 = 0;
p1RotateTimer.stop();
}
}
public function PTurretRotate(Evt:Event){
var Mouse1x:Number;
var Mouse1y:Number;
var Mouse1Angle:Number;
Mouse1x = mvi_PTurret1.x - mouseX;
Mouse1y = mvi_PTurret1.y - mouseY;
Mouse1Angle = Math.round(Math.atan2(Mouse1y,Mouse1x) * (180/Math.PI) + 180);
if(Turret1SpinDirection == 0 && Mouse1Angle < 90 && PTurret1angle > 270){
Mouse1Angle = Math.round(Math.atan2(Mouse1y,Mouse1x) * (180/Math.PI) + 180)+ 360;
}
else if(Turret1SpinDirection == 1 && Mouse1Angle > 270 && PTurret1angle < 90){
Mouse1Angle = Math.round(Math.atan2(Mouse1y,Mouse1x) * (180/Math.PI) + 180)- 360;
}
if(PTurret1angle > 360){
PTurret1angle = 1;
}
if(PTurret1angle < 0){
PTurret1angle = 359;
}
if(PTurret1angle < Math.round(player1angle) - 210 || PTurret1angle > Math.round(player1angle) - 150){
if(Mouse1Angle > PTurret1angle){
mvi_PTurret1.rotation += 1;
PTurret1angle += 1;
Turret1SpinDirection = 0;
}
else if(Mouse1Angle < PTurret1angle){
mvi_PTurret1.rotation -= 1;
PTurret1angle -= 1;
Turret1SpinDirection = 1;
}
}
else{
if(PTurret1angle == Math.round(player1angle) - 210){
mvi_PTurret1.rotation -= 1;
PTurret1angle -= 1;
}
else if(Math.round(player1angle) - 210 < 0){
if(PTurret1angle + 90 == Math.round(player1angle) - 210 + 90){
mvi_PTurret1.rotation -= 1;
PTurret1angle -= 1;
}
}
if(PTurret1angle == Math.round(player1angle) - 150){
mvi_PTurret1.rotation += 1;
PTurret1angle += 1;
}
}
var Mouse2x:Number;
var Mouse2y:Number;
var Mouse2Angle:Number;
Mouse2x = mvi_PTurret2.x - mouseX;
Mouse2y = mvi_PTurret2.y - mouseY;
Mouse2Angle = Math.round(Math.atan2(Mouse2y,Mouse2x) * (180/Math.PI) + 180);
if(Turret2SpinDirection == 0 && Mouse2Angle < 90 && PTurret2angle > 270){
Mouse2Angle = Math.round(Math.atan2(Mouse2y,Mouse2x) * (180/Math.PI) + 180)+ 360;
}
else if(Turret2SpinDirection == 1 && Mouse2Angle > 270 && PTurret2angle < 90){
Mouse2Angle = Math.round(Math.atan2(Mouse2y,Mouse2x) * (180/Math.PI) + 180)- 360;
}
if(PTurret2angle > 360){
PTurret2angle = 1;
}
if(PTurret2angle < 0){
PTurret2angle = 359;
}
if(Mouse2Angle > PTurret2angle){
mvi_PTurret2.rotation += 1;
PTurret2angle += 1;
Turret2SpinDirection = 0;
}
else if(Mouse2Angle < PTurret2angle){
mvi_PTurret2.rotation -= 1;
PTurret2angle -= 1;
Turret2SpinDirection = 1;
}
//txt_Turret1Angle.text = Mouse1Angle.toString();
//txt_PTurret.text = PTurret1angle.toString();
}
public function mouseCoordinate(Evt:Event){
//txt_X.text = mouseX.toString();
//txt_Y.text = mouseY.toString();
PTurretRotateTimer.start();
}
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);
stage.addEventListener(Event.ENTER_FRAME, enterFrame);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
stage.frameRate = 30;
addChild(game);
}
private function mouseMove(e :MouseEvent) :void {
Game.mouse.x = e.stageX;
Game.mouse.y = e.stageY;
}
private function enterFrame(e :Event) :void {
game.update();
}
}
}
Thank you very much.

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());

Actionscript 3.0 - MouseEvents not working

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.

Game Over function is not working Starling

I've been following a tutorial over the web but it somehow did not show something about creating a game over function. I am new to the Starling framework and Actionscript so I'm kind of still trying to find a way to make it work. Here's the complete snippet of the code.
package screens
{
import flash.geom.Rectangle;
import flash.utils.getTimer;
import events.NavigationEvent;
import objects.GameBackground;
import objects.Hero;
import objects.Item;
import objects.Obstacle;
import starling.display.Button;
import starling.display.Image;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.text.TextField;
import starling.utils.deg2rad;
public class InGame extends Sprite
{
private var screenInGame:InGame;
private var screenWelcome:Welcome;
private var startButton:Button;
private var playAgain:Button;
private var bg:GameBackground;
private var hero:Hero;
private var timePrevious:Number;
private var timeCurrent:Number;
private var elapsed:Number;
private var gameState:String;
private var playerSpeed:Number = 0;
private var hitObstacle:Number = 0;
private const MIN_SPEED:Number = 650;
private var scoreDistance:int;
private var obstacleGapCount:int;
private var gameArea:Rectangle;
private var touch:Touch;
private var touchX:Number;
private var touchY:Number;
private var obstaclesToAnimate:Vector.<Obstacle>;
private var itemsToAnimate:Vector.<Item>;
private var scoreText:TextField;
private var remainingLives:TextField;
private var gameOverText:TextField;
private var iconSmall:Image;
static private var lives:Number = 2;
public function InGame()
{
super();
this.addEventListener(starling.events.Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(event:Event):void {
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
drawGame();
scoreText = new TextField(300, 100, "Score: 0", "MyFontName", 35, 0xD9D919, true);
remainingLives = new TextField(600, 100, "Lives: " + lives +" X ", "MyFontName", 35, 0xD9D919, true);
iconSmall = new Image(Assets.getAtlas().getTexture("darnahead1"));
iconSmall.x = 360;
iconSmall.y = 40;
this.addChild(iconSmall);
this.addChild(scoreText);
this.addChild(remainingLives);
}
private function drawGame():void {
bg = new GameBackground();
this.addChild(bg);
hero = new Hero();
hero.x = stage.stageHeight / 2;
hero.y = stage.stageWidth / 2;
this.addChild(hero);
startButton = new Button(Assets.getAtlas().getTexture("startButton"));
startButton.x = stage.stageWidth * 0.5 - startButton.width * 0.5;
startButton.y = stage.stageHeight * 0.5 - startButton.height * 0.5;
this.addChild(startButton);
gameArea = new Rectangle(0, 100, stage.stageWidth, stage.stageHeight - 250);
}
public function disposeTemporarily():void {
this.visible = false;
}
public function initialize():void {
this.visible = true;
this.addEventListener(Event.ENTER_FRAME, checkElapsed);
hero.x = -stage.stageWidth;
hero.y = stage.stageHeight * 0.5;
gameState ="idle";
playerSpeed = 0;
hitObstacle = 0;
bg.speed = 0;
scoreDistance = 0;
obstacleGapCount = 0;
obstaclesToAnimate = new Vector.<Obstacle>();
itemsToAnimate = new Vector.<Item>();
startButton.addEventListener(Event.TRIGGERED, onStartButtonClick);
//var mainStage:InGame =InGame.current.nativeStage;
//mainStage.dispatchEvent(new Event(Event.COMPLETE));
//playAgain.addEventListener(Event.TRIGGERED, onRetry);
}
private function onStartButtonClick(event:Event):void {
startButton.visible = false;
startButton.removeEventListener(Event.TRIGGERED, onStartButtonClick);
launchHero();
}
private function launchHero():void {
this.addEventListener(TouchEvent.TOUCH, onTouch);
this.addEventListener(Event.ENTER_FRAME, onGameTick);
}
private function onTouch(event:TouchEvent):void {
touch = event.getTouch(stage);
touchX = touch.globalX;
touchY = touch.globalY;
}
private function onGameTick(event:Event):void {
switch(gameState) {
case "idle":
if(hero.x < stage.stageWidth * 0.5 * 0.5) {
hero.x += ((stage.stageWidth * 0.5 * 0.5 + 10) - hero.x) * 0.05;
hero.y = stage.stageHeight * 0.5;
playerSpeed += (MIN_SPEED - playerSpeed) * 0.05;
bg.speed = playerSpeed * elapsed;
} else {
gameState = "flying";
}
break;
case "flying":
if(hitObstacle <= 0) {
hero.y -= (hero.y - touchY) * 0.1;
if(-(hero.y - touchY) < 150 && -(hero.y - touchY) > -150) {
hero.rotation = deg2rad(-(hero.y - touchY) * 0.2);
}
if(hero.y > gameArea.bottom - hero.height * 0.5) {
hero.y = gameArea.bottom - hero.height * 0.5;
hero.rotation = deg2rad(0);
}
if(hero.y < gameArea.top + hero.height * 0.5) {
hero.y = gameArea.top + hero.height * 0.5;
hero.rotation = deg2rad(0);
}
} else {
hitObstacle--
cameraShake();
}
playerSpeed -= (playerSpeed - MIN_SPEED) * 0.01;
bg.speed = playerSpeed * elapsed;
scoreDistance += (playerSpeed * elapsed) * 0.1;
scoreText.text = "Score: " + scoreDistance;
initObstacle();
animateObstacles();
createEggItems();
animateItems();
remainingLives.text = "Lives: "+lives + " X ";
if(lives == 0) {
gameState = "over";
}
break;
case "over":
gameOver();
break;
}
}
private function gameOver():void {
gameOverText = new TextField(800, 400, "Hero WAS KILLED!!!", "MyFontName", 50, 0xD9D919, true);
scoreText = new TextField(800, 600, "Score: "+scoreDistance, "MyFontName", 30, 0xFFFFFF, true);
this.addChild(scoreText);
this.addChild(gameOverText);
playAgain = new Button(Assets.getAtlas().getTexture("button_tryAgain"));
playAgain.x = stage.stageWidth * 0.5 - startButton.width * 0.5;
playAgain.y = stage.stageHeight * 0.75 - startButton.height * 0.75;
this.addChild(playAgain);
playAgain.addEventListener(Event.TRIGGERED, onRetry);
}
private function onRetry(event:Event):void {
playAgain.visible = false;
gameOverText.visible = false;
scoreText.visible = false;
var btnClicked:Button = event.target as Button;
if((btnClicked as Button) == playAgain) {
this.dispatchEvent(new NavigationEvent(NavigationEvent.CHANGE_SCREEN, {id: "playnow"}, true));
}
disposeTemporarily();
}
private function animateItems():void {
var itemToTrack:Item;
for(var i:uint = 0; i < itemsToAnimate.length; i++) {
itemToTrack = itemsToAnimate[i];
itemToTrack.x -= playerSpeed * elapsed;
if(itemToTrack.bounds.intersects(hero.bounds)) {
itemsToAnimate.splice(i, 1);
this.removeChild(itemToTrack);
}
if(itemToTrack.x < -50) {
itemsToAnimate.splice(i, 1);
this.removeChild(itemToTrack);
}
}
}
private function createEggItems():void {
if(Math.random() > 0.95){
var itemToTrack:Item = new Item(Math.ceil(Math.random() * 10));
itemToTrack.x = stage.stageWidth + 50;
itemToTrack.y = int(Math.random() * (gameArea.bottom - gameArea.top)) + gameArea.top;
this.addChild(itemToTrack);
itemsToAnimate.push(itemToTrack);
}
}
private function cameraShake():void {
if(hitObstacle > 0) {
this.x = Math.random() * hitObstacle;
this.y = Math.random() * hitObstacle;
} else if(x != 0) {
this.x = 0;
this.y = 0;
lives--;
}
}
private function initObstacle():void {
if(obstacleGapCount < 1200) {
obstacleGapCount += playerSpeed * elapsed;
} else if(obstacleGapCount !=0) {
obstacleGapCount = 0;
createObstacle(Math.ceil(Math.random() * 5), Math.random() * 1000 + 1000);
}
}
private function animateObstacles():void {
var obstacleToTrack:Obstacle;
for(var i:uint = 0; i<obstaclesToAnimate.length; i++) {
obstacleToTrack = obstaclesToAnimate[i];
if(obstacleToTrack.alreadyHit == false && obstacleToTrack.bounds.intersects(hero.bounds)) {
obstacleToTrack.alreadyHit = true;
obstacleToTrack.rotation = deg2rad(70);
hitObstacle = 30;
playerSpeed *= 0.5;
}
if(obstacleToTrack.distance > 0) {
obstacleToTrack.distance -= playerSpeed * elapsed;
} else {
if(obstacleToTrack.watchOut) {
obstacleToTrack.watchOut = false;
}
obstacleToTrack.x -= (playerSpeed + obstacleToTrack.speed) * elapsed;
}
if(obstacleToTrack.x < -obstacleToTrack.width || gameState == "over") {
obstaclesToAnimate.splice(i, 1);
this.removeChild(obstacleToTrack);
}
}
}
private function checkElapsed(event:Event):void {
timePrevious = timeCurrent;
timeCurrent = getTimer();
elapsed = (timeCurrent - timePrevious) * 0.001;
}
private function createObstacle(type:Number, distance:Number):void{
var obstacle:Obstacle = new Obstacle(type, distance, true, 300);
obstacle.x = stage.stageWidth;
this.addChild(obstacle);
if(type >= 4) {
if(Math.random() > 0.5) {
obstacle.y = gameArea.top;
obstacle.position = "top"
} else {
obstacle.y = gameArea.bottom - obstacle.height;
obstacle.position = "bottom";
}
} else {
obstacle.y = int(Math.random() * (gameArea.bottom - obstacle.height - gameArea.top)) + gameArea.top;
obstacle.position = "middle";
}
obstaclesToAnimate.push(obstacle);
}
}
}
You're not calling initialize() anywhere, which is where the gameState is initially set to "idle" it seems... what does this code do currently when you run it?
The goal here is to get the onGameTick(event) function running every frame, which is going to switch between idle/flying/over game states.