Labyrinth/maze game - actionscript-3

I'm creating a very simple game in Flash AS3 including labyrinth. Here's the code:
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;
oseba.addEventListener(Event.ENTER_FRAME, premik);
oseba.addEventListener( Event.ENTER_FRAME, handleCollision)
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
var keys:Array = [];
function keyDownHandler(e:KeyboardEvent):void{
keys[e.keyCode] = true;
}
function keyUpHandler(e:KeyboardEvent):void{
keys[e.keyCode] = false;
}
function premik(e:Event):void{
if (keys[Keyboard.RIGHT]) {
oseba.x += 5;
}
if (keys[Keyboard.LEFT]) {
oseba.x -= 5;
}
if (keys[Keyboard.UP]) {
oseba.y -= 5;
}
if (keys[Keyboard.DOWN]) {
oseba.y += 5;
}
}
function handleCollision(e:Event ):void{
if(oseba.hitTestObject(nazaj)){
gotoAndPlay(2,"igra");
}
if(oseba.hitTestObject(gozd)){
gotoAndPlay(2);
}
I'd like to add collision detection, that will disallow my ''oseba'' that is walking around from walking over unmarked terrain. Below I've created a non visible MC ''potke''. I supposed the best way would be to calculate ''oseba'' 's next position and if it's on ''potke'' then ''oseba'' can't move there. I'm looking for suitable example of code, cos I've tried few different already, but non seems to work.
I'm also receiving the following error:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at XYgame_fla::MainTimeline/handleCollision()
Everything seems to work fine otherwise, but this error keeps showing up.

I would try using nazaj.hitTestPoint(oseba.x, oseba,y, true) and put the EventListener to the stage to fix the error.

Related

I want to make a shooting game with animate AS3, and i stuck with with this code

I want to improve this coding of mine but i cant find a way. so everytime i press "space" the bullet came out from the object, and if i pressed it again, the bullet that already called to the stage will reset its coordination, instead of calling another one. or can u only called one child at a time? is there any way for me to calling many child instead of just 1?
import flash.events.KeyboardEvent;
import flash.events.Event;
var fl_MyInstance:bullet = new bullet();
function move(event:Event):void
{
if(fl_MyInstance.hitTestObject(wall))
{
removeChild(fl_MyInstance);
stage.removeEventListener(Event.ENTER_FRAME, move);
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, summon);
function summon(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.SPACE){
addChild(fl_MyInstance);
fl_MyInstance.x = hero.x
fl_MyInstance.y = hero.y
stage.addEventListener(Event.ENTER_FRAME, move);
}
}
stage.addEventListener(Event.ENTER_FRAME, gerak);
function gerak(e:Event):void
{
fl_MyInstance.y += 5;
}

AS3 Keyboard Movement Error

Im making a game and have written the code to move my sprite with the arrow keys. For some reason, these two errors pop up.
LINE 34
Warning: 1090: Migration Issue: The onKeyDown event handler is not triggered automatically by Flash Player at run time in Actionscribpt 3.0. You must first register this handler for the event using addEventListener ('keyDown' callback_handler).
LINE 39
Warning: 1090: Migration Issue: The onKeyUp event handler is not triggered automatically by Flash Player at run time in Actionscribpt 3.0. You must first register this handler for the event using addEventListener ('keyUp' callback_handler).
This is my code for the movement
stop();
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;
Wizard.addEventListener(Event.ENTER_FRAME, KeyClick);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
var keys:Array = [];
function KeyClick(e:Event):void
{
if (keys[Keyboard.RIGHT])
{
Wizard.x += 5;
}
if (keys[Keyboard.LEFT])
{
Wizard.x -= 5;
}
if (keys[Keyboard.UP])
{
Wizard.y -= 5;
}
if (keys[Keyboard.DOWN])
{
Wizard.y += 5;
}
}
function onKeyDown(e:KeyboardEvent):void
{
keys[e.keyCode] = true;
}
function onKeyUp(e:KeyboardEvent):void
{
keys[e.keyCode] = false;
}
How do i fix these errors? Thanks :)
Those are just warnings; the reason they're there is because in ActionScript 2, events worked like:
target.onKeyUp = function()
{
//
}
target.onKeyDown = function()
{
//
}
I assume the warnings are triggered because you've used the same naming convention for your handler functions as the old style of handling these events.
If they bother you, simply rename them to something else.

Problems getting keyboard input in AS3

So I'm workin on a flash project where I want keyboard input. In the stage there's an instance "Car" seen from above which is supposed to be rotate and drive direction of rotation. This is what I've put together so far in AS3:
//Required stuff
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.display.Stage;
import flash.display.MovieClip;
Car.addEventListener(Event.ENTER_FRAME, this.RunGame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
//Variables
var keys:Array = []
var vDrive:Number = 3; //Car's current base speed
var vx:Number = 0; //Speed along x axis
var vy:Number = 0; //Speed along y axis
var vMax:Number = 30; //Top speed
var vRot:Number = 3; //Rotation speed
var vAcc:Number = 1.1; //Factor for acceleration
var vDeAcc:Number = 0.90; //Factor for de-acceleration
//Game Loop
RunGame();
function RunGame():void
{
// Drive forwards
if (keys[Keyboard.UP])
{
if (vDrive < vMax)
vDrive += vAcc;
}
// Reverse
if (keys[Keyboard.DOWN])
{
if (vDrive > vMax)
vDrive *= vAcc;
}
// Turn right
if (keys[Keyboard.RIGHT])
{
Car.rotation += vRot;
}
// Turn left venstre
if (keys[Keyboard.LEFT])
{
Car.rotation -= vRot;
}
//Movement
// Friction
vDrive *= vDeAcc;
//Calculating movement vector
vx = vDrive * Math.cos(toRad(Car.rotation));
vy = vDrive * Math.sin(toRad(Car.rotation));
//Update car position
Car.x -= vx ;
Car.y -= vy;
}
However, when I run the program, the arrow keys don't seem to do anything.
I also get the following compiler warnings for both "onKeyDown" and "onKeyUp":
Migration issue: The onKeyDown event handler is not triggered
automatically by Flash Player at run time in ActionScript 3.0. You
must first register this handler for the event using addEventListener
( 'keyDown', callback_handler)
Trying to add what it suggested just makes errors saying callback_handler ain't defined.
I'm now stuck trying to figure out how to make the keyboard input work. Anyone know?
You are currently missing the functions for the key listeners. You have added the listeners to the stage here:
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
Now you just need to create the functions:
function onKeyDown( e:KeyboardEvent ):void {
//add our key to the keys array
keys[e.keyCode] = e.keyCode;
}
function onKeyUp( e:KeyboardEvent ):void {
//if the key is in the keys array, set the value to null
keys[e.keyCode] = null;
}
But there is another problem here:
Car.addEventListener(Event.ENTER_FRAME, this.RunGame);
You do not need the this.RunGame, just RunGame will do, but you should get an error this method needs a parameter of type Event, so your RunGame() definition should look like this:
function RunGame(e:Event):void
Then you wouldn't call RunGame(), it is called each frame while tied to the event listener.
Edit: Please note that there are many ways to handle key events, my answer will work with your current implementation.

Actionscript 3.0, error with hitTestObject

I'm getting an error I can't seem to fix. I think I know kind of what is going on but I'm not sure enough to be able to fix it. I keep getting error
"TypeError: Error #2007: Parameter hitTestObject must be non-null.
at flash.display::DisplayObject/_hitTest()
at flash.display::DisplayObject/hitTestObject()"
Basically I fire an attack in my game. It hits an enemy and he is killed just fine. BUT, he has an animation as he dies that takes a couple seconds. It seems if I fire another attack during his animation, my attack IMMEDIATELY gives this error (before striking anything, that is). Once the animation is over, everything is fine again. Also, the game was working 100% fine before I put in this animation.
Here is my document class
package com.classes
{
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
public class DocumentClass extends MovieClip
{
// we need to keep track of our enemies.
public static var enemyList1:Array = new Array();
// moved stickobject1 to a class variable.
private var stickobject1:Stickman2;
public function DocumentClass() : void
{
//removed the var stickobject1:Stickman2 because we declared it above.
var bg1:background1 = new background1();
stage.addChild(bg1);
stickobject1 = new Stickman2(stage);
stage.addChild(stickobject1);
stickobject1.x=50;
stickobject1.y=300;
//running a loop now.... so we can keep creating enemies randomly.
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
//our loop function
private function loop(e:Event) : void
{
//run if condition is met.
if (Math.floor(Math.random() * 90) == 5)
{
//create our enemyObj1
var enemyObj1:Enemy1 = new Enemy1(stage, stickobject1);
//listen for enemyObj1 being removed from stage
enemyObj1.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemyObj1, false, 0, true);
//add our enemyObj1 to the enemyList1
enemyList1.push(enemyObj1);
stage.addChild(enemyObj1);
}
}
private function removeEnemyObj1(e:Event)
{
enemyList1.splice(enemyList1.indexOf(e.currentTarget), 1);
}
}
}
And here is my attack1 class
package com.classes {
import flash.display.MovieClip;
import flash.display.Stage;
import com.senocular.utils.KeyObject;
import flash.ui.Keyboard;
import flash.events.Event;
public class attack1 extends MovieClip {
private var stageRef:Stage;
private var bulletSpeed:Number = 16;
public function attack1 (stageRef:Stage, x:Number, y:Number) : void
{
this.stageRef = stageRef;
this.x = x;
this.y = y;
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
private function loop(e:Event) : void
{
//move bullet up
x += bulletSpeed;
if (x > stageRef.stageWidth)
removeSelf();
for (var i:int = 0; i < DocumentClass.enemyList1.length; i++)
{
if (hitTestObject(DocumentClass.enemyList1[i].hit))
{
trace("hitEnemy");
removeSelf();
DocumentClass.enemyList1[i].takeHit();
}
}
}
private function removeSelf() : void
{
removeEventListener(Event.ENTER_FRAME, loop);
if (stageRef.contains(this))
stageRef.removeChild(this);
}
}
}
Don't think you should need any other of my classes to figure out what's going on, but let me know if you do! Thanks very much =)
You don't want to do a hit test against any object that may have been removed from the scene (or from the enemyList array). The extra condition added to attack1.loop's for loop should get rid of your error. A better fix is to splice out the items you remove, so they are never tested against in the loop.
The break line will make it stop trying to hit other enemies after the bullet is removed. If the line "DocumentClass.enemyList1[i].takeHit();" removes the item from the enemyList1, you need to make sure you use "i--;" at the bottom of the loop as well, if you plan on looping through the remainder of the enemies. "i--" or "break", you will probably need one of them in that loop.
Double check the order in which you are executing your removal methods. Sometimes it's better to flag the items for removal and remove them in a separate loop than to remove an item that may be needed later in the same loop.
for (var i:int = 0; i < DocumentClass.enemyList1.length; i++){
if(DocumentClass.enemyList1[i] && DocumentClass.enemyList1[i].hit){
if (hitTestObject(DocumentClass.enemyList1[i].hit)){
trace("hitEnemy");
removeSelf();
DocumentClass.enemyList1[i].takeHit();
break;
}
}
}
Not the correct solution in this question. You can always do != null in a conditional statement.
if(object!=null){
party.drink();
}

hitTestObject collision detection not working in as3!

I am trying to create a platformer game and i am trying to make "player1" stop when it hits a "platform". here is my code so far,
gotoAndStop("gameStart");
import flash.display.MovieClip;
import flash.events.*;
import flash.ui.Keyboard;
import flash.ui.*;
import flash.utils.Timer;
import flash.events.TimerEvent;
player1.gotoAndStop("nothing");
//private var speed:Number = 0;
//private var maxspeed:Number = 4;
var myTimer:Timer = new Timer(10,0);
stage.focus = this;
player1.addEventListener(Event.ENTER_FRAME,enterFrameHandler);
/*
myTimer.addEventListener(TimerEvent.TIMER,someFunction);
myTimer.start();
function someFunction(event:TimerEvent) {
player1.y += 2;
}
*/
function setup() {
stage.addEventListener(KeyboardEvent.KEY_DOWN, reactToArrowKeys);
}
setup();
function reactToArrowKeys(keyEvent:KeyboardEvent) {
if (keyEvent.keyCode == 37) {
if (player1.x > 0) {
player1.x -= 5;
}
} else if (keyEvent.keyCode == 39) {
if (player1.x < 700) {
player1.x += 5;
}
}
}
function enterFrameHandler(e:Event):void {
if (player1.hitTestObject(platform)) {
trace("hitting");
} else {
player1.y += 4;
}
}
however the hitTestObject function (enterFrameHandler) does not work properly and will always take the "else" route.
please help!
The code as posted works fine for me. I'd look for some other kind of silly mistake - for example, if you copied and pasted movie clips, you might have more than one clip on the stage named "platform", in which case your reference may not resolve to the one you intend. Or something else along those lines.
To track it down, try calling:
trace( player1.getBounds(stage) );
trace( platform.getBounds(stage) );
which will tell you where Flash thinks the bounding boxes of those clips are. My guess is that code will return something other than what you'd expect, and resolving that discrepancy will show where the bug is.