I'm trying to make an array that creates 4 coins (which I've done), but the problem is I'm trying to move the coins downward, and I can't figure out how to access the array list to move the coins down(commented out lenght[i].y +=4) which doesn't work. The other problem is I want to only create 4 coins, and not 4 coins every frame in the update loop.
Thanks.
public class Coin extends Sprite
{
//..SPRITES
public static var coinSprite:CoinSprite;
public var _coins:Array = new Array();
public var c = new CoinSprite();
public static var COINCOUNT:int = 4;
//-------------------------------------------------------------------------|
//##SETUP------------------------------------------------------------------|
//-------------------------------------------------------------------------|
public function Coin()
{
super();
this.addEventListener(starling.events.Event.ADDED_TO_STAGE, stageSetup);
}
public function stageSetup(event:Event):void {
this.removeEventListener(Event.ADDED_TO_STAGE, stageSetup);
}
//-------------------------------------------------------------------------|
//-------------------------------------------------------------------------|
//##MANAGER----------------------------------------------------------------|
//-------------------------------------------------------------------------|
public function manager():void {
this.addEventListener(Event.ENTER_FRAME, updateCoin);
}
//-------------------------------------------------------------------------|
//-------------------------------------------------------------------------|
//##COINHANDLER------------------------------------------------------------|
//-------------------------------------------------------------------------|
public function coinHandler():void {
var length:Number = 4;
for ( var i:Number = 0; i < length; i++) {
//length[i].y += 4;
createCoin();
c.y = i * 50;
}
}
//-------------------------------------------------------------------------|
//-------------------------------------------------------------------------|
//##COLLISION||------------------------------------------------------------|
//-------------------------------------------------------------------------|
public function hitCoinPlayer():void {
//..cleanup
if (c.hitTestObject(Player.playerSprite)) {
c.alpha = 0;
}
//..check bounds
if (c.y >= 1500) {
c.y = -200;
c.alpha = 1;
}
}
//-------------------------------------------------------------------------|
//-------------------------------------------------------------------------|
//##UPDATE-----------------------------------------------------------------|
//-------------------------------------------------------------------------|
public function updateCoin(e:Event):void {
//coinHandler();
}
//-------------------------------------------------------------------------|
//-------------------------------------------------------------------------|
//##CREATE COIN------------------------------------------------------------|
//-------------------------------------------------------------------------|
public function createCoin():void {
c = new CoinSprite();
c.x = 305;
Starling.current.nativeOverlay.addChild(c);
_coins.push(c);
}
//-------------------------------------------------------------------------|
}
public var _coins:Array = {}; // you need an array to store the coins you've created
public function stageSetup(event:Event):void {
coinHandler(); //create four coins upon setting up the stage
this.removeEventListener(Event.ADDED_TO_STAGE, stageSetup); //done setup
}
//other parts of the code are not changed
public function coinHandler():void { // you only need to call this once from ur stagesetup
var length:Number = 4;
for ( var i:Number = 0; i < length; i++) {
createCoin();
c.y = i * 50;
}
}
public function updateCoin(e:Event):void {
moveCoin();
}
public function moveCoin(){
for ( var i:Number = 0; i < _coins.length; i++) {
_coins[i].y +=4;
}
}
public function createCoin():void {
c = new CoinSprite();
c.x = 305;
Starling.current.nativeOverlay.addChild(c);
_coins.push(c);
}
Related
I don't get any errors but my script doesn't load or possibly save my array...
here's the first script
[System.Serializable]
public class PlayerData
{
public float health;
public float thirst;
public float hunger;
public float oxygen;
public float[] position;
public int[] inventoryIDs;
public PlayerData (Health healthO, SaveLoad saveload)
{
//Save int items
health = healthO.health;
thirst = healthO.thirst;
hunger = healthO.hunger;
oxygen = healthO.oxygen;
//set and save location array
position = new float[3];
position[0] = healthO.transform.position.x;
position[1] = healthO.transform.position.y;
position[2] = healthO.transform.position.z;
//set and save inventory IDs
inventoryIDs = new int[50];
for(int i = 0; i < 50; i++)
{
inventoryIDs[i] = saveload.IDs[i];
}
}
}
here's the next
public class SaveLoad : MonoBehaviour
{
public GameObject player;
public int[] IDs;
public GameObject[] objects;
Inventory inventory;
Health health;
void Start()
{
IDs = new int[50];
objects = new GameObject[50];
inventory = player.GetComponent<Inventory>();
health = player.GetComponent<Health>();
}
void Update()
{
//Add IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = inventory.slot[i].GetComponent<Slot>().ID;
}
//debug save load test
if (Input.GetKeyDown(KeyCode.Z))
{
SaveP();
}
if (Input.GetKeyDown(KeyCode.X))
{
LoadP();
}
}
public void SaveP()
{
SaveSystem.SavePlayer(health, this);
}
public void LoadP()
{
PlayerData data = SaveSystem.LoadPlayer();
//load stats
health.thirst = data.thirst;
health.hunger = data.hunger;
health.health = data.health;
health.oxygen = data.oxygen;
//Load position
Vector3 position;
position.x = data.position[0];
position.y = data.position[1];
position.z = data.position[2];
player.transform.position = position;
//load IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = data.inventoryIDs[i];
}
//Load Items
for (int i = 0; i < 50; i++)
{
if(objects[IDs[i]] != null)
{
GameObject itemObject = (GameObject)Instantiate(objects[IDs[i]], new Vector3(0, 0, 0), Quaternion.identity);
Item item = itemObject.GetComponent<Item>();
inventory.AddItem(itemObject, item.ID, item.type, item.name, item.description, item.icon);
} else
{
return;
}
}
}
}
Here's the last script
public static class SaveSystem
{
public static string fileName = "FileSave.bin";
public static void SavePlayer(Health health, SaveLoad SL)
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
// Create file stream
FileStream file = File.Create(GetFullPath());
//Save data
PlayerData data = new PlayerData(health, SL);
bf.Serialize(file, data);
//Close stream
file.Close();
}
public static PlayerData LoadPlayer()
{
if (SaveExists())
{
try
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
//Create file stream
FileStream file = File.Open(GetFullPath(), FileMode.Open);
//Load data
PlayerData pd = (PlayerData)bf.Deserialize(file);
//close stream
file.Close();
//return data
return pd;
}
catch (SerializationException)
{
Debug.Log("Failed to load file at: " + GetFullPath());
}
}
return null;
}
private static bool SaveExists()
{
return File.Exists(GetFullPath());
}
private static string GetFullPath()
{
return Application.persistentDataPath + "/" + fileName;
}
}
there are all connected with the save load script loading and saving the variables into the player and items to the inventory sots. the inventory IDs array isn't saving or loading
I'm making a basic Galaga type game in Flash and have been running into issues. This is my first time really messing with ActionScript.
I created an Array for my Enemies and would like to know how I would go about having them spawn in their own respective locations, like in Galaga and then have them move uniformly form left to right while descending once reaching the edge of the stage.
Game
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class SpaceVigilanteGame extends MovieClip
{
public var army:Array;
public var avatar:Avatar;
public var gameTimer:Timer;
public var useMouseControl:Boolean;
public var rightKeyIsBeingPressed:Boolean;
public var leftKeyIsBeingPressed:Boolean;
var gameWidth:int = 0;
var gameHeight:int = 0;
public function SpaceVigilanteGame()
{ useMouseControl = false;
leftKeyIsBeingPressed = false;
rightKeyIsBeingPressed = false;
army = new Array();
var newEnemy = new Enemy( 60, 30 );
army.push( newEnemy );
addChild( newEnemy );
avatar = new Avatar();
addChild( avatar );
if ( useMouseControl )
{
avatar.x = mouseX;
avatar.y = mouseY;
}
else
{
avatar.x = 50;
avatar.y = 400;
}
gameWidth = stage.stageWidth;
gameHeight = stage.stageHeight;
gameTimer = new Timer( 25 );
gameTimer.addEventListener( TimerEvent.TIMER, moveEnemy );
gameTimer.addEventListener( TimerEvent.TIMER, moveAvatar );
gameTimer.start();
stage.addEventListener( KeyboardEvent.KEY_DOWN, onKeyPress );
stage.addEventListener( KeyboardEvent.KEY_UP, onKeyRelease );
function onKeyPress( keyboardEvent:KeyboardEvent ):void
{
if ( keyboardEvent.keyCode == Keyboard.RIGHT )
{
rightKeyIsBeingPressed = true;
}
else if ( keyboardEvent.keyCode == Keyboard.LEFT )
{
leftKeyIsBeingPressed = true;
}
}
function onKeyRelease( keyboardEvent:KeyboardEvent ):void
{
if ( keyboardEvent.keyCode == Keyboard.RIGHT )
{
rightKeyIsBeingPressed = false;
}
else if (keyboardEvent.keyCode ==Keyboard.LEFT )
{
leftKeyIsBeingPressed = false;
}
}
}
public function moveEnemy( timerEvent:TimerEvent ):void
{
for each ( var enemy:Enemy in army )
{
}
//enemy.moveDownABit();
if(enemy.x+enemy.width+2<=gameWidth)
{
enemy.moveRight();
}
else if(enemy.y+enemy.height+2<=gameHeight)
{
enemy.moveDown();
}
else if(enemy.x-2>=0)
{
enemy.moveLeft();
}
else if(enemy.y-2>=0)
{
enemy.moveUp();
}
}
public function moveAvatar( timerEvent:TimerEvent ):void
{
if ( useMouseControl )
{
avatar.x = mouseX;
avatar.y = mouseY;
}
else if ( rightKeyIsBeingPressed )
{
avatar.moveRight();
}
else if ( leftKeyIsBeingPressed )
{
avatar.moveLeft();
}
}
}
}
Enemy Class
package
{
import flash.display.MovieClip;
public class Enemy extends MovieClip
{
public function Enemy( startX:Number, startY:Number )
{
x = startX;
y = startY;
}
public function moveRight():void
{
x = x + 2;
}
public function moveDown():void
{
y = y + 2;
}
public function moveLeft():void
{
x = x - 2;
}
public function moveUp():void
{
y = y - 2;
}
}
}
I would suggest that during the enemy instantiation (of which there seems to be only one), you should be setting the locations respective of one another.
as an example:
your code currently does this:
var newEnemy = new Enemy( 60, 30 );
army.push( newEnemy );
addChild( newEnemy );
Perhaps it should do something like this:
for(var x:int = 0; x< ARMY_WIDTH; x++)
{
for(var y:int = 0; y < ARMY_HEIGHT; y++)
{
army.push(new Enemy(60 + x * X_GAP, 30 + y *Y_GAP));
this.addChild(army[army.length-1]);
}
}
Now, I've made a lot of assumptions in the above code; I've invented constants that you may not have, and I've only solved your immediate problem. Ideally you're going to need to look at more advanced solutions for your issue, something like a factory class that creates your enemies for you, or recycles them from a pool of enemies.
However, you're just starting out and you will figure a lot of this stuff out in time. Good luck in your project and I hope you keep up developing your skills :)
I am trying to create a cone of vision for my enemy class. Right now it checks to see if the player is within a radius before moving towards them and will move around randomly if they are not. I want to give it vision so the enemy does not always rotate towards the player.
Enemy Class
package
{
import flash.automation.ActionGenerator;
import flash.events.Event;
import flash.geom.Point;
public class Enemy extends GameObject
{
var isDead:Boolean = false;
var speed:Number = 3;
var originalValue:Number = 50;
var changeDirection:Number = originalValue;
var checkDirection:Number = 49;
var numberGen:Number;
//var startTime:int = getTimer();
//var $timer = getTimer();
//var myTimer:int = getTimer();
//var moveTimer:int = timer - $timer;
public function Enemy()
{
super();
target = target_mc;
}
override public function update():void
{
movement();
}
private function movement():void
{
if (changeDirection >= 0)
{
if (changeDirection > checkDirection)
{
numberGen = (Math.random() * 360) / 180 * Math.PI;
}
var velocity:Point = new Point();
var $list:Vector.<GameObject > = getType(Player);
var $currentDistance:Number = Number.MAX_VALUE;
for (var i:int = 0; i < $list.length; i++)
{
var currentPlayer:GameObject = $list[i];
if (MathUtil.isWithinRange(currentPlayer.width,currentPlayer.x,currentPlayer.y,width,x,y))
{
var $delta:Point = new Point ;
$delta.x = currentPlayer.x - x;
$delta.y = currentPlayer.y - y;
if ($currentDistance > $delta.length)
{
$currentDistance = $delta.length;
velocity = $delta;
velocity.normalize(speed);
}
}
}
if(velocity.length == 0)
{
velocity = Point.polar(2, numberGen);
}
changeDirection--;
if (changeDirection == 0)
{
changeDirection = originalValue;
}
}
velocity.x = Math.floor(velocity.x * 10) * .1;
velocity.y = Math.floor(velocity.y * 10) * .1;
moveBy([Wall, Door], velocity.x, velocity.y, collides_mc);
var $collides:GameObject = collision([Player]);
if ($collides != null)
{
destroy();
}
if ($collides == null)
{
$collides = collision([Player],this);
if ($collides != null)
{
$collides.destroy();
}
}
rotation = (Math.atan2(velocity.y, velocity.x) * 180 / Math.PI);
collides_mc.rotation = -rotation;
trace($collides);
}
override public function onCollideX($collision:GameObject):void
{
}
override public function onCollideY($collision:GameObject):void
{
}
}
}
GameObject Class, which contains all the functions and Enemy extends it
package
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.sensors.Accelerometer;
import flashx.textLayout.elements.ListElement;
public class GameObject extends MovieClip
{
static public var list:Vector.<GameObject> = new Vector.<GameObject>;
protected var hitBox:Sprite;
public var target:MovieClip;
public function GameObject()
{
target=this;
list.push(this);
}
public function update():void
{
}
public function collision(typesColliding:Array, $target:DisplayObject = null):GameObject
{
if($target == null)
$target = target;
for (var i:int = list.length - 1; i >= 0; i--)
{
var item:GameObject = list[i], found:Boolean = false;
for (var f:int = typesColliding.length - 1; f >= 0; f--)
{
if (item is typesColliding[f])
{
found = true;
break;
}
}
if (found && $target.hitTestObject(item.target) && this != item)
{
return item;
}
}
return null;
}
public function moveBy(typesColliding:Array, $x:Number = 0, $y:Number = 0, $target:DisplayObject = null):void
{
var $collision:GameObject;
x += $x;
if (($collision = collision(typesColliding, $target)) != null)
{
x -= $x;
onCollideX($collision);
}
y += $y;
if (($collision = collision(typesColliding, $target)) != null)
{
y -= $y;
onCollideY($collision);
}
}
public function onCollideX($collision:GameObject):void
{
}
public function onCollideY($collision:GameObject):void
{
}
public function getType($class:Class):Vector.<GameObject>
{
var $list:Vector.<GameObject> = new Vector.<GameObject>;
for (var i:int = 0; i < list.length; i++)
{
if (list[i] is $class)
{
$list.push(list[i]);
}
}
return $list;
}
public function destroy():void
{
var indexOf:int = list.indexOf(this);
if (indexOf > -1)
list.splice(indexOf, 1);
if (parent)
parent.removeChild(this);
trace("removing item: "+this+" list: " + list.length + ": " + list);
}
}
}
Any help would be appreciated, thank you.
Changing radius of vision to the cone of vision simply requires computing (after checking the distance) the angle between the direction enemy is facing and the player. If this angle is smaller then some T, then it is in the cone of vision of angle 2T (due to symmetry).
This obviously ignores any walls/obstacles that should limit vision, but it should give you the general idea.
I have seen many threads about this but my problem doesn't solved. This may be a simple way but i have no idea...
I'm trying to get Objects indices in an array like so :
var test:Array = new Array();
for (var row:Number = 0; row < 2; row++) {
test[row] = [];
for (var column:Number = 0; column < 3; column++) {
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
test[row][column] = new ballShape(column, column, row);
addChild(test[row][column]);
}
}
function objClicked(evt:MouseEvent):void {
// Here must return Object index in array
}
P.S :
I can get items index in int array, but i don't know about objects.
Any ideas would be appreciated.
Edit :
ballShape.as
package {
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.MouseEvent;
import fl.motion.Color;
public class ballShape extends Sprite {
private var shapeId:uint;
private var currentPosition:uint;
private var arrayPosition:uint;
private var color:Number;
public function ballShape(Id:uint, currPos:uint, arrPos:uint) {
setId(Id);
setArrayPos(arrPos);
setCurrentPos(currPos);
//trace("Array : " + arrPos);
//trace("Curr : " + currPos);
if (arrPos == 0) {
var posX:uint = 60;
} else {
var posX:uint = (arrPos + 1) * 60;
}
if (currPos == 0) {
var posY:uint = 42;
} else {
var posY:uint = (currPos + 1) * 42;
}
if (arrPos == 0) {
color = 0xFF0000;
} else {
color = 0x00FF00;
}
graphics.beginFill(color, 1.0);
graphics.drawCircle(posX, posY, 20);
graphics.endFill();
this.addEventListener(MouseEvent.CLICK, Clicked);
}
public function setId(Id:uint):void {
shapeId = Id;
}
public function getId():uint {
return shapeId;
}
public function Clicked(evt:MouseEvent):void {
//return getId();
trace("Ball id is " + getId());
trace("Array id is " + getArrayPos());
trace("PositionInArray id is " + getCurrentPos());
//return arrayPosition;
}
public function setCurrentPos(Pos:uint):void {
currentPosition = Pos;
}
public function getCurrentPos():uint {
return currentPosition;
trace(currentPosition);
}
public function setArrayPos(arrayPos:uint):void {
arrayPosition = arrayPos;
}
public function getArrayPos():uint {
return arrayPosition;
trace(arrayPosition);
}
public function addBead(arrayId, currPos):void {
}
}
}
I would suggest adding row and column as public variables in your ballShape class.
That way you can get them like this:
function objClicked(evt:MouseEvent):void {
trace(ballShape(evt.target).getCurrentPos(), ballShape(evt.target).getArrayPos());
}
Maybe turn this two lines around:
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
test[row][column] = new ballShape(column, column, row);
to be :
test[row][column] = new ballShape(column, column, row);
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
Try something like:
protected function objClicked(e:MouseEvent):void {
for (var row: int=0; row < test.length; row++) {
var column:int = (test[row] as Array).indexOf(e.currentTarget);//use currentTarget so you don't try to match on internal Interactive Objects!
if (column>-1) {
trace(row, column);
return;//or break, if you need to do something else below this loop
}
}
}
I am in need of some help. I am very new to actionscript and what I am trying to do is calculate the amount of apples from the array and then trace it in the main function. Right now I am getting an error on the return and that error is 1067: Implicit coercion of a value of type String to an unrelated type Number. Now I have tried to switch out the number and string but I still get the error.
public class extends Sprite
{
public function()
{
var fruitNames:Array = ["apple", "peach","banana","pear","guava","apple","peach"];
var totalApples:Number = countingApples(fruitNames);
trace("You have " + totalApples);
}
private function countingApples(fruitNames:Array):Number
{
var total:String = "apple";
for(var i:uint=0; i<7; i++)
{
total += Number[i];
}
return total;
}
}
public class extends Sprite
{
public function()
{
var fruitNames:Array = ["apple", "peach","banana","pear","guava","apple","peach"];
var totalApples:Number = countingApples(fruitNames);
trace("You have " + totalApples);
}
private function countingApples(fruitNames:Array):Number
{
var total:uint = 0;
var i:String = new String();
for(i in fruitNames) {
if (fruitNames[i] == "apple") {
total = total + 1;
}
}
return total;
}
}
That error is because you're trying to return total, which is a String, but you've set the countingApples function's return type as Number. Here's an example which will do what you want, but I think you should try writing your own version again so that you know what's going on:
private function countingApples(fruitNames:Array):Number
{
var total:uint = 0;
var targetFruit:String = "apple";
var totalFruit:uint = fruitNames.length;
for(var i:uint = 0; i < totalFruit; i++)
{
if (fruitNames[i] == targetFruit) {
total++;
}
}
return total;
}