What's the AS3 equivalent of the following AS2 code? - actionscript-3

I'm trying to translate the following AS2 code into AS3 because I have Adobe Flash CC, which doesn't, as far as I know (from research, trial and error), support AS2 code. Any help would be greatly appreciated...
onClipEvent(load) {
speed = 0;
acceleration = 0.4;
speedDecay = 0.96;
maxSpeed = 10;
backSpeed = 1;
}
onClipEvent(enterFrame) {
if(Math.abs(speed) > 0.3) {
speed *= speedDecay;
}else {
speed = 0;
}
if(Key.isDown(Key.UP)) {
if (Math.abs(speed) >= maxspeed) {
speed += acceleration;
}
}
if(Key.isDown(Key.DOWN)) {
if(speed < 0.5)
speed = -2;
else
speed--;
}
if (Math.abs(speed)> 0.5) {
if (Key.isDown(Key.LEFT)) {
_rotation -= 10;
}
if (Key.isDown(Key.RIGHT)) {
_rotation += 10;
}
}
x = Math.sin(_rotation*(Math.PI/180))*speed;
y = Math.cos(_rotation*(Math.PI/180))*speed*-1;
if (!_root.ground.hitTest(_x+x, _y+y, true)) {
_x += x;
_y += y;
}else {
speed -= speed*1.5;
}
}
This code goes in the Car layer of my car game.

Put this code inside your car's movieclip on frame 1:
var speed: Number = 0;
var acceleration: Number = 0.4;
var speedDecay: Number = 0.96;
var maxSpeed: Number = 10;
var backSpeed: Number = 1;
var pressedKeys: Object = {}
stage.addEventListener(Event.ENTER_FRAME, loop)
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown)
stage.addEventListener(KeyboardEvent.KEY_UP, keyup)
function keydown(e: KeyboardEvent) {
pressedKeys[e.keyCode] = true
}
function keyup(e: KeyboardEvent) {
if (pressedKeys[e.keyCode]) {
pressedKeys[e.keyCode] = false
}
}
function loop(e: Event) {
if (Math.abs(speed) > 0.3) {
speed *= speedDecay;
} else {
speed = 0;
}
if (pressedKeys[Keyboard.UP]) {
if (Math.abs(speed) >= maxSpeed) {
speed += acceleration;
}
}
if (pressedKeys[Keyboard.DOWN]) {
if (speed < 0.5)
speed = -2;
else
speed--;
}
if (Math.abs(speed) > 0.5) {
if (pressedKeys[Keyboard.LEFT]) {
this.rotation -= 10;
}
if (pressedKeys[Keyboard.RIGHT]) {
this.rotation += 10;
}
}
var vx: Number = Math.sin(this.rotation * (Math.PI / 180)) * speed;
var vy: Number = Math.cos(this.rotation * (Math.PI / 180)) * speed * -1;
if (!MovieClip(root).ground.hitTestPoint(this.x + vx, this.y + vy, true)) {
this.x += vx;
this.y += vy;
} else {
speed -= speed * 1.5;
}
}

Related

How do I add gravity in a simple game?

So I've been making a simple game and I want gravity, but I don't know where to start. I
would like it if I could change the speed that the pieces fall, but whatever works best is fine. Could someone please help me because I have no idea.
Here's my code so far...
Also, this is modified to fit the small preview, so full screening won't work very well.
canvas {
border: 1px solid #000;
}
<HTML>
<canvas id="canvas" style="position: absolute; left: 0px; top: 0px;"></canvas>
<script>
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.width = innerWidth-4;
canvas.height = innerHeight-10;
canvas.style.backgroundColor = '#87CEEB';
var x = 150,
y = 180,
velY = 0,
velX = 0,
speed = 2,
friction = 0.95,
keys = [];
function update() {
requestAnimationFrame(update);
if (keys[87]) {
if (velY > -speed) {
velY--;
}
}
if (keys[68]) {
if (velX < speed) {
velX++;
}
}
if (keys[65]) {
if (velX > -speed) {
velX--;
}
}
if (keys[38]) {
if (velY > -speed) {
velY--;
}
}
if (keys[39]) {
if (velX < speed) {
velX++;
}
}
if (keys[37]) {
if (velX > -speed) {
velX--;
}
}
velY *= friction;
y += velY;
velX *= friction;
x += velX;
if (x >= 1345) {
x = 1345;
} else if (x <= 5) {
x = 5;
}
if (y > 180) {
y = 180;
} else if (y <= 5) {
y = 5;
}
ctx.clearRect(0, 0, 2000, 1000);
ctx.beginPath(),
player = new component(x, y, 'black', 10, 10);
ctx.fill();
}
function component(x, y, color, width, height) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
update();
document.body.addEventListener('keydown', function(e) {
keys[e.keyCode] = true;
});
document.body.addEventListener('keyup', function(e) {
keys[e.keyCode] = false;
});
</script>
</html>

Access of possibly undefined property alpha through a reference with static type Class

I'm not sure how to go about setting the transparency when the character's health goes down.
Error is on line 38
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.ui.Keyboard;
public class Character extends MovieClip
{
var velocity:Number;
var shootLimiter:Number;
var health:Number;
var maxHealth:Number;
public function Character()
{
velocity = 10;
shootLimiter = 0;
health = 100;
maxHealth = 100;
addEventListener("enterFrame", move);
x = 300
y = 150
}
function takeDamage(d)
{
health -= d;
if(health <= 0)
{
health = 0;
kill();
}
Game.healthMeter.bar.scaleX = health/maxHealth;
Character.alpha = health/100;
}
function kill()
{
var blood = new Blood();
stage.addChild(blood);
blood.x = this.x;
blood.y = this.y;
removeEventListener("enterFrame",move);
this.visible = false;
Game.gameOver();
}
function move(e:Event)
{
shootLimiter += 5;
if(Key.isDown(Keyboard.RIGHT))
{
if(this.x <= 560)
{
this.x = this.x + velocity;
}
}
if(Key.isDown(Keyboard.LEFT))
{
if(this.x >= 40)
{
this.x = this.x - velocity;
}
}
if(Key.isDown(Keyboard.UP))
{
if(this.y > 20)
{
this.y = this.y - velocity;
}
}
if(Key.isDown(Keyboard.DOWN))
{
if(this.y < 280)
{
this.y = this.y + velocity;
}
}
if(Key.isDown(Keyboard.SPACE) && shootLimiter > 8)
{
shootLimiter = 0;
var b = new Needles();
stage.addChild(b);
b.x = this.x+65;
b.y = this.y+45;
}
}
}
}
Character has no static property called alpha. You are referring to the instance of the class and therefore it should be this.alpha = health/100; instead of Character.alpha = health/100;

set boundaries in flash

I want to set boundaries to my movie clip in flash with as3 so that the movie clip can't move out of the stage. How can i do this? This is the code that i have now. How i can now set the boundaries?
bij_mc.links_mc.play();
bij_mc.rechts_mc.play();
stage.addEventListener(KeyboardEvent.KEY_DOWN,beweeg);
stage.addEventListener(KeyboardEvent.KEY_UP,stopbeweeg);
function beweeg(evt:KeyboardEvent):void {
if (evt.keyCode==Keyboard.LEFT) {
bij_mc.links_mc.x -=10;
bij_mc.rechts_mc.x -=10;
bij_mc.lichaam_mc.x -=10;
bij_mc.links_mc.stop();
bij_mc.rechts_mc.play();
bij_mc.rotation = -5;
} else if (evt.keyCode==Keyboard.RIGHT) {
bij_mc.links_mc.x +=10;
bij_mc.rechts_mc.x +=10;
bij_mc.lichaam_mc.x += 10;
bij_mc.links_mc.play();
bij_mc.rechts_mc.stop();
bij_mc.rotation = 5;
} else if (evt.keyCode==Keyboard.UP) {
bij_mc.links_mc.y -=10;
bij_mc.rechts_mc.y -= 10;
bij_mc.lichaam_mc.y -= 10;
bij_mc.links_mc.play();
bij_mc.rechts_mc.play();
bij_mc.rotation = 0;
} else if (evt.keyCode==Keyboard.DOWN) {
bij_mc.links_mc.y +=10;
bij_mc.rechts_mc.y += 10;
bij_mc.lichaam_mc.y += 10;
bij_mc.links_mc.stop();
bij_mc.rechts_mc.stop();
bij_mc.rotation = 0;
}
}
function stopbeweeg(evt:KeyboardEvent):void {
bij_mc.links_mc.play();
bij_mc.rechts_mc.play();
bij_mc.rotation = 0;
}
stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
private function onEnterFrame(event:Event):void
{
// update beweeg
checkBoundaries()
}
private function checkBoundaries():void
{
// left
if (bij_mc.x < 0)
bij_mc.x = 0;
// right
else if (bij_mc.x > stage.stageWidth)
bij_mc.x = stage.stageWidth - bij_mc.width;
// top
if (bij_mc.y < 0)
bij_mc.y = 0;
// bottom
else if (bij_mc.y > stage.stageHeight)
bij_mc.y = stage.stageHeight - bij_mc.height;
}
Update each movie clip accordingly.

AS3 indexof array object property

I'm trying to complete background in kind of Space Invaders game. I want to generate stars at a random location, scroll them to the bottom of the stage and then add new star after each one is gone. I guess that the problem lies on the indexOf method, which I tried to use to find star y proprety.
I know this may be a stupid mistake, i'm a beginner :)
My current main class:
public class Main extends Sprite
{
private var ship:Ship = new Ship();
private var numStars:int = 80;
private var starArray:Array = new Array();
public function Main():void
{
stage.addChild(ship);
ship.x = stage.stageWidth / 2 - ship.width / 2;
ship.y = stage.stageHeight / 2 - ship.height / 2;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
for (var i:int = 0; i < numStars; i++)
{
createStar();
}
}
public function createStar():void
{
var newStar:Star = new Star();
starArray.push(newStar);
stage.addChildAt(newStar,1);
newStar.x = Math.random() * stage.stageWidth;
newStar.y = Math.random() * stage.stageHeight;
newStar.alpha = Math.random();
newStar.rotation = Math.random()*360;
newStar.scaleX = Math.random();
newStar.scaleY = Math.random();
}
public function keyDownHandler(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.UP)
{
ship.accelerationY = -0.3;
}
if (e.keyCode == Keyboard.DOWN)
{
ship.accelerationY = 0.3;
}
if (e.keyCode == Keyboard.LEFT)
{
ship.accelerationX = -0.3;
}
if (e.keyCode == Keyboard.RIGHT)
{
ship.accelerationX = 0.3;
}
}
public function keyUpHandler(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.UP || e.keyCode == Keyboard.DOWN)
{
ship.accelerationX = 0;
ship.accelerationY = 0;
}
if (e.keyCode == Keyboard.LEFT || e.keyCode == Keyboard.RIGHT)
{
ship.accelerationY = 0;
ship.accelerationX = 0;
}
}
public function enterFrameHandler(e:Event):void
{
//acceleration
ship.vx += ship.accelerationX;
ship.vy += ship.accelerationY;
//friction
ship.vx *= ship.friction;
ship.vy *= ship.friction;
if (Math.abs(ship.vx) < 0.1)
{
ship.vx = 0;
}
if (Math.abs(ship.vy) < 0.1)
{
ship.vy = 0;
}
ship.rotation = ship.vx * 2;
//set speed limit
if (ship.vx > ship.speedLimit)
{
ship.vx = ship.speedLimit;
}
if (ship.vx < -ship.speedLimit)
{
ship.vx = -ship.speedLimit;
}
if (ship.vy > ship.speedLimit)
{
ship.vy = ship.speedLimit;
}
if (ship.vy < -ship.speedLimit)
{
ship.vy = -ship.speedLimit;
}
//set stage boundaries
if (ship.x < 0)
{
ship.x = 0;
}
if (ship.y < 0)
{
ship.y = 0;
}
if (ship.x + ship.width > stage.stageWidth)
{
ship.x = stage.stageWidth - ship.width;
}
if (ship.y + ship.height > stage.stageHeight)
{
ship.y = stage.stageHeight - ship.height;
}
ship.x += ship.vx;
ship.y += ship.vy;
//star enter frame code
for (var i:int = 0; i < numStars; i++)
{
starArray[i].y += 0.5 + Math.random() * 2;
}
if (starArray.indexOf(starArray.y) > stage.stageHeight) //if y property of any star is higher than stage height, create a new star
{
createStar();
}
}
}
i recommend looking into tween utilities like TweenLite which do time based animations: (http://www.greensock.com/tweenlite/)
also recommend looking into object pooling, reused objects instead of creating new ones. Good thing to learn as a new programmer.
you are correct about where your issue lies
i got your program working correctly with the following change:
---------change these lines-------------
//star enter frame code
for (var i:int = 0; i < numStars; i++)
{
starArray[i].y += 0.5 + Math.random() * 2;
}
if (starArray.indexOf(starArray.y) > stage.stageHeight) //if y property of any star is higher than stage height, create a new star
{
createStar();
}
---------to this-------------
//star enter frame code
for (var i:int = 0; i < numStars; i++)
{
var star:Star = starArray[i];
star.y += 0.5 + Math.random() * 2;
if (star.y>stage.stageHeight){
//dont create a new star -- memory leak
//move the same star to a new random location
star.y = 0;
}
}
Instead of just creating a new star, why not just replace it at the top outside of the screen?
As for indexOf, it only returns the index in an array of the object being passed. And in this case you're passing the y value of an array, which doesn't have that property.
Instead, move your position checking code to your for loop in the game loop. That way, you already have an index (your i variable) of the star that's outside the boundaries and if it is, just reposition it and save some memory!
for (var i:int = 0; i < numStars; i++)
{
starArray[i].y += 0.5 + Math.random() * 2;
if(starArray[i].y > stage.stageHeight)
{
// Repositions the star between x: 0 to stageWidth, y: -5 to -15
starArray[i].y = Math.random() * -10 - 5;
starArray[i].x = Math.random() * stage.stageWidth;
}
}

Button only clickable when visible

Ok i want my button to only be clickabe once it is visibe, it is invisible til you win the game(1 score of pong)
here is what i have
var buttonsStates:Object = {
"scoreBoard_W" : false
};
function checkVisibility () {
for (var scoreBoard_W:String in buttonsStates) {
if(visible == true)
{
scoreBoard_W.addEventListener(MouseEvent.CLICK, goto3);
function goto3(Event:MouseEvent)
{
gotoAndStop(1,"Menu");
}
and here is the error: Pong, Layer 'Pong', Frame 2, Line 129 1061: Call to a possibly undefined method addEventListener through a reference with static type String.
im not sure what it means, or if im on the right track any help is apperciaed
Here is all of the code
stop();
var buttonsStates:Object = {
"scoreBoard_W" : false
};
var ballSpeedX:int = -3;
var ballSpeedY:int = -2;
var cpuPaddleSpeed:int = 3;
var playerScore:int = 0;
var cpuScore:int = 0;
scoreBoard_W.visible = false;
scoreBoard_L.visible = false;
init();
function init():void
{
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function calculateBallAngle(paddleY:Number, ballY:Number):Number
{
var ySpeed:Number = 5 * ((ballY - paddleY) / 25);
return ySpeed;
}
function updateTextFields():void
{
playerScoreText.text = ("Player Score: " + playerScore);
cpuScoreText.text = ("CPU Score: " + cpuScore);
}
function loop(e:Event):void
{
if (playerPaddle.hitTestObject(ball) == true)
{
if (ballSpeedX < 0)
{
ballSpeedX *= -1;
ballSpeedY = calculateBallAngle(playerPaddle.y, ball.y);
}
}
else if (cpuPaddle.hitTestObject(ball) == true )
{
if (ballSpeedX > 0)
{
ballSpeedX *= -1;
ballSpeedY = calculateBallAngle(cpuPaddle.y, ball.y);
}
}
if (cpuPaddle.y < ball.y - 10)
{
cpuPaddle.y += cpuPaddleSpeed;
}
else if (cpuPaddle.y > ball.y + 10)
{
cpuPaddle.y -= cpuPaddleSpeed;
}
playerPaddle.y = mouseY;
if (playerPaddle.y - playerPaddle.height / 2 < 0)
{
playerPaddle.y = playerPaddle.height / 2;
}
else if (playerPaddle.y + playerPaddle.height/2 > stage.stageHeight)
{
playerPaddle.y = stage.stageHeight - playerPaddle.height / 2;
}
ball.x += ballSpeedX;
ball.y += ballSpeedY;
if (ball.x <= ball.width / 2)
{
ball.x = ball.width / 2;
ballSpeedX *= -1;
cpuScore++;
updateTextFields();
}
else if (ball.x >= stage.stageWidth-ball.width/2)
{
ball.x = stage.stageWidth - ball.width / 2;
ballSpeedX *= -1;
playerScore++;
updateTextFields();
}
if (ball.y <= ball.height / 2)
{
ball.y = ball.height / 2;
ballSpeedY *= -1;
}
else if (ball.y >= stage.stageHeight-ball.height/2)
{
ball.y = stage.stageHeight - ball.height / 2;
ballSpeedY *= -1;
}
if (playerScore >= 1)
{
stage.removeEventListener(Event.ENTER_FRAME, loop);
scoreBoard_W.visible = true;
}
if (cpuScore >= 1)
{
stage.removeEventListener(Event.ENTER_FRAME, loop);
scoreBoard_L.visible = true;
}
}
Mouse.hide();
mywelcome.text = "Good Luck, " + myName;
function checkVisibility () {
for (var scoreBoard_W:String in buttonsStates) {
if(visible == true)
{
scoreBoard_W.addEventListener(MouseEvent.CLICK, goto3);
function goto3(Event:MouseEvent)
{
gotoAndStop(1,"Menu");
}
}
}
}
The problem is in this line
scoreBoard_W.addEventListener(MouseEvent.CLICK, goto3);
As you using for (var scoreBoard_W:String in buttonsStates){...} inside definition of function function checkVisibility () {...} you declare local String-type variable which block your access to button with same name.
Changing
scoreBoard_W.addEventListener(MouseEvent.CLICK, goto3);
to
this.scoreBoard_W.addEventListener(MouseEvent.CLICK, goto3);
will do the trick.