Math random in action script3 - actionscript-3

I am making a game and I am trying to create an array of the same object falling in multiple spots. I would also like to have them fall at different spots, using the math random. The problem that I am encountering is that the objects (bananas) don't show up on the screen at all. Can math random be used on the y-axis in action script 3? If so, could someone give me an example?
This is what I have in the main program:
var numBananas = 20;
var theBananas: Array = new Array();
theBananas = [];
for (var i = 0; i < numBananas; i++) {
var aBanana: banana_fall = new banana_fall();
aBanana.y=-10;
theBananas.push(aBanana);
theBananas[i].setSpeed(-(Math.random()), 5);
And this is what I have in the action script class:
package {
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.Event;
public class banana_fall extends MovieClip {
var velX: Number = 0;
var velY: Number = 0;
var falling: Boolean = false;
var gravity: Number = 2;
public function banana_fall() {
var timing: Timer = new Timer(20, 0);
timing.addEventListener(TimerEvent.TIMER, moveMe);
timing.start();
}
private function moveMe(event: TimerEvent) {
this.x = this.x + velX;
this.y = this.y + velY;
if (falling) {
falling=true;
velY = velY + gravity;
}
}
public function setSpeed(dx, dy) {
velX = dx;
velY = dy;
}
}
}

I think the problem is within this method:
private function moveMe(event: TimerEvent)
{
this.x = this.x + velX;
this.y = this.y + velY;
if (falling)
{
falling=true;
velY = velY + gravity;
}
}
You set negative velocity and falling is false initially so gravity never works. Your bananas go bananas, they appear above the screen and flee up into the open space of negative y.
As a general rule, you need to trace(...) things to understand what's the problem. Also, there's no need to explicitly use this in class methods:
private function moveMe(event: TimerEvent)
{
x += velX;
y += velY;
if (falling) velY += gravity;
trace("[BANANA] position:", x, y, "speed:", velX, velY);
}

Related

Creat Boundaries

Hello Everyone again :) I'm having an issue with boundaries actually about creating boundaries. In my stage I got 2 mc's names : Dispenser and Puller. Dispenser creating particles and puller is pulling them. I just need to set a boundary like a path.
But i couldn't so asking for your help :)
Bdw the code is from this site : http://www.freeactionscript.com/?s=puller&x=0&y=0
package
{
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends Sprite
{
// you can play around with these
private var particlesTotal:Number = 50;
private var particleSpeed:Number = 10;
private var particleFadeoutSpeed:Number = .0175;
// don't change these
private var particlesCurrent:Number = 0;
private var particlesArray:Array;
private var radians:Number;
private var _sayac:uint;
public function Main():void
{
init();
}
private function init():void
{
radians = 180 / Math.PI;
particlesArray = [];
addEventListener(Event.ENTER_FRAME, onEnterFrameLoop);
dispenser_mc.addEventListener(MouseEvent.MOUSE_DOWN, onThingDown);
puller_mc.addEventListener(MouseEvent.MOUSE_DOWN, onThingDown);
dispenser_mc.addEventListener(MouseEvent.MOUSE_UP, onThingUp);
puller_mc.addEventListener(MouseEvent.MOUSE_UP, onThingUp);
}
private function onThingDown(event:MouseEvent):void
{
event.currentTarget.startDrag();
}
private function onThingUp(event:MouseEvent):void
{
event.currentTarget.stopDrag();
}
private function createParticle(target1:MovieClip, target2:MovieClip):void
{
if(particlesTotal <= particlesCurrent)
{
return;
}
particlesCurrent++;
var tempParticle:Particle = new Particle();
tempParticle.x = (target1.x - target1.width / 2) + (Math.random() * target1.width);
tempParticle.y = (target1.y - target1.height / 2) + (Math.random() * target1.height);
tempParticle.rotation = Math.random()*360;
tempParticle.rot = Math.atan2(target1.y - target2.y, target1.x - target2.x);
tempParticle.xSpeed = Math.cos(tempParticle.rot) * radians / particleSpeed;
tempParticle.ySpeed = Math.sin(tempParticle.rot) * radians / particleSpeed;
tempParticle.mass = tempParticle.width / 2 + tempParticle.height / 2;
particlesArray.push(tempParticle);
addChild(tempParticle);
}
private function updateParticle():void
{
for (var i = 0; i < particlesArray.length; i++)
{
var tempParticle:MovieClip = particlesArray[i];
tempParticle.x -= tempParticle.xSpeed;
tempParticle.y -= tempParticle.ySpeed;
tempParticle.alpha -= particleFadeoutSpeed;
// I know i can set boundries here but idk how to so :)
if(tempParticle.hitTestObject(puller_mc))
{
destroyParticle(tempParticle);
_sayac++;
trace(_sayac);
}
else if (tempParticle.alpha <= 0)
{
destroyParticle(tempParticle);
}
else if (tempParticle.x < 0)
{
destroyParticle(tempParticle);
}
else if (tempParticle.x > stage.stageWidth)
{
destroyParticle(tempParticle);
}
else if (tempParticle.y < 0)
{
destroyParticle(tempParticle);
}
else if (tempParticle.y > stage.stageHeight)
{
destroyParticle(tempParticle);
}
}
}
private function destroyParticle(particle:MovieClip):void
{
for (var i = 0; i < particlesArray.length; i++)
{
var tempParticle:MovieClip = particlesArray[i];
if (tempParticle == particle)
{
particlesCurrent--;
particlesArray.splice(i,1);
removeChild(tempParticle);
}
}
}
private function onEnterFrameLoop(event:Event):void
{
createParticle(dispenser_mc, puller_mc);
updateParticle();
}
}
}
actually there is no boundary in this code. let me explain the main parts of this code for you:
this is the most important part:
tempParticle.rot = Math.atan2(target1.y - target2.y, target1.x - target2.x);
tempParticle.xSpeed = Math.cos(tempParticle.rot) * radians / particleSpeed;
tempParticle.ySpeed = Math.sin(tempParticle.rot) * radians / particleSpeed;
rot is the angle to reach the puller.
xSpeed is how much the particle should go to right  every frame to reach the puller.
ySpeed is how much the particle should go to down every frame to reach the puller.
and in updateParticle function, the partcle will move, according to xSpeed and ySpeed.
so the correct xSpeed and YSpeed will cause particles to go straight.not a boundary !
I   h ☻ p e   I explained good and ,
I   h ☺ p e   this helps !

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

How to make a movieClip move independent of the stage if added on it?

In my flash-made game, if my character jump on top of an enemy movieclip it spawns 3 minions from another class by MovieClip(root).addChild(spawn1);. In my minions class I've put the code for them to fall and stop upon hitting the ground and also follow my character.
I have a VCam(virtual camera) movieClip to follow my character(who moves on the stage, not the stage around him) with this code build-in:
import flash.events.Event;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.geom.Point;
import flash.display.MovieClip;
//VCam
addEventListener(Event.ENTER_FRAME, handleEnterFrame);
function handleEnterFrame(event:Event):void {
if (parent) {
parent.scaleX = 1 / scaleX;
parent.scaleY = 1 / scaleY;
if (rotation == 0) {
parent.x = (width / 2 - x) / scaleX;
parent.y = (height / 2 - y) / scaleY;
parent.rotation = 0;
} else {
var bounds:Rectangle = getBounds(this);
var angle:Number = rotation * Math.PI / 180;
var midX:Number = -x / scaleX;
var midY:Number = -y / scaleY;
var rx:Number = -bounds.width / 2;
var ry:Number = -bounds.height / 2;
var cos:Number = Math.cos(angle);
var sin:Number = Math.sin(angle);
var rotatedX:Number = rx * cos - ry * sin;
var rotatedY:Number = ry * cos + rx * sin;
var cornerX:Number = midX - rotatedX;
var cornerY:Number = midY - rotatedY;
cos = Math.cos(-angle);
sin = Math.sin(-angle);
parent.x = cornerX * cos - cornerY * sin;
parent.y = cornerY * cos + cornerX * sin;
parent.rotation = -rotation;
}
}
}
addEventListener(Event.REMOVED, handleRemoved, false, 0, true);
function handleRemoved(event:Event):void
{
removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
removeEventListener(Event.REMOVED, handleRemoved);
}
When I jump with my character it seems that the minions follow the movement of my vcam and not behaving normally, jumping with the camera and falling throu'the ground when the character falls.
If I add a child normally from the main timeline by addChild(m_clip); it does not behave like that.
Is there an easy fix? Thanks!
This is the minions class code:
package {
import flash.display.*;
import flash.events.*;
public class EnemySpawned extends MovieClip {
protected var gravitysp: Number = 1;
protected var ySpeedsp: Number = 0;
protected var Speedsp: Number = 6.5;
var charMTL:MovieClip;
public function EnemySpawned()
{
this.addEventListener(Event.ENTER_FRAME, movement);
trace('exist');
}
function movement(event:Event):void
{
var MTL:MovieClip = MovieClip(root);
charMTL = MTL.char1;
ySpeedsp += gravitysp;
if(! MTL.ground_1.hitTestPoint(this.x, this.y, true))
{
this.y += ySpeedsp;
}
if(ySpeedsp > 40)
{
ySpeedsp = 40;
}
for(var j:int = 0; j<20; j++)
{
if(MTL.ground_1.hitTestPoint(this.x, this.y, true))
{
this.y--
ySpeedsp = 0;
}
}
var Distance:Number = charMTL.x - this.x;
if(Distance < -charMTL.width/2 - this.width/2)
{
this.x -= Speedsp;
}
if(Distance > charMTL.width/2 + this.width/2)
{
this.x += Speedsp;
}
}
}
}
There is no moving of ground_1 movieClip via code.

AS3 game character only shoots in one direction

I'm making a top down shooter game and so far my character can move and can shoot when mouse is click. But it will only shoot to the right and not where my cursor is pointing. How do i fix this?
Here's the bullet code in the main class:
public var bulletList:Array = [];
stage.addEventListener(MouseEvent.CLICK, shootBullet, false, 0, true);
stage.addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
public function shootBullet(e:MouseEvent):void
{
var bullet:Bullet = new Bullet(stage, harold.x, harold.y, harold.rotation);
bullet.addEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved, false, 0, true);
bulletList.push(bullet);
stage.addChild(bullet);
}
public function loop(e:Event):void
{
if(bulletList.length > 0)
{
for(var i:int = bulletList.length-1; i >= 0; i--)
{
bulletList[i].loop();
}
}
}
public function bulletRemoved(e:Event):void
{
e.currentTarget.removeEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved);
bulletList.splice(bulletList.indexOf(e.currentTarget),1);
}
Here is the code in my Bullet Class:
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
public class Bullet extends MovieClip
{
private var stageRef:Stage;
private var speed:Number = 10;
private var xVel:Number = 0;
private var yVel:Number = 0;
private var rotationInRadians = 0;
public function Bullet(stageRef:Stage, X:int, Y:int, rotationInDegrees:Number):void
{
this.stageRef = stageRef;
this.x = X;
this.y = Y;
}
public function loop():void
{
xVel = Math.cos(rotationInRadians) * speed;
yVel = Math.sin(rotationInRadians) * speed;
x += xVel;
y += yVel;
if(x > stageRef.stageWidth || x < 0 || y > stageRef.stageHeight || y < 0)
{
this.parent.removeChild(this);
}
}
}
}
A few thoughts:
As said by Aaron, you should compute rotationInRadians in the constructor, altought the real formula is this.rotationInRadians = rotationInDegrees * (Math.PI / 180);
You should make rotationInRadians a number, that is private var rotationInRadians:Number;
Are you aware displayObject has a getter/setter for rotation? In other words: harold.rotation is a property in harold object or is it referencing to said getter?
I think thats pretty much it.
I think you forgot to assign rotationInRadians in your constructor:
this.rotationInRadians = rotationInDegrees * (Math.PI / 180);
BTW, unless you want the bullet to be able to change direction during flight, you don't need to calculate the xVel and yVel each loop(), you can just calculate it in the constructor, store it, then update the x and y each loop().

How Do I make my ship stay on the stage?

What code should I put in here to make my ship stay in the stage?
My ship keeps going off the stage when I press the keys and it goes too far. How do I get it to bump into walls and make it stay on the stage?
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.ui.Keyboard;
public class Ship extends MovieClip{
var velocity:Number;
var shootLimiter:Number;
var health:Number;
var maxHealth:Number;
function Ship(){
velocity = 10;
shootLimiter = 0;
health = 100;
maxHealth = 100;
addEventListener("enterFrame", move);
}
function kill(){
var explosion = new Explosion();
stage.addChild(explosion);
explosion.x = this.x;
explosion.y = this.y;
removeEventListener("enterFrame", move);
this.visible = false;
Game.gameOver();
}
function takeDamage(d){
health -= d;
if(health<=0){
health = 0;
kill();
}
Game.healthMeter.bar.scaleX = health/maxHealth;
}
function move(e:Event){
shootLimiter += 1;
if(Key.isDown(Keyboard.D)){
this.x = this.x + velocity;
}
if(Key.isDown(Keyboard.A)){
this.x = this.x - velocity;
}
if(Key.isDown(Keyboard.W)){
this.y = this.y - velocity;
}
if(Key.isDown(Keyboard.S)){
this.y = this.y + velocity;
}
if(Key.isDown(Keyboard.SPACE) && shootLimiter > 8){
shootLimiter = 0;
var b = new Bullet();
stage.addChild(b);
b.x = this.x + 40;
b.y = this.y + -25;
}
if(shield.visible == true){
shield.alpha -= 0.0005;
if(shield.alpha == 0){
shield.visible = false;
shield.alpha = 1;
}
}
}
}
}
Your code is hard to fix as it is, but I'll give you an answer in pseudo, so you could think on how to implement it to fit in your project. Your ship is going out of the frame because it has no notion of where to stop. Lets say the ship x and y coordinates are taken from the upper left corner of the sprite, as it is in actionscript, then, every time your ship moves to the left, you must consider the following:
if(Key.isDown(Keyboard.A)){
var futureX:Number = this.x - velocity;
if (futureX <= 0){ //your ship has reached the left border of the screen
this.x = 0;
} else {
this.x = futureX;
}
}
things get a little more complicated when you're checking for the right or bottom border of the screen, as you need to consider the size of your stage and the size of your sprite in the calculations:
if(Key.isDown(Keyboard.S)){
var futureY:Number = this.y + velocity;
if (futureY + this.height >= Stage.stageHeight){
this.y = Stage.stageHeight - this.height;
} else {
this.y = futureY;
}
}
The solution for the top and right borders are trivial after this.