AS3 Keyboard Movement Error - actionscript-3

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.

Related

How to remove a tween before moving to next frame in as3

I have a movieclip which spins. I want it when users drag and drop it to stop spinning and be in it's initial position. I wrote this code but i get error TypeError: Error #1009: Cannot access a property or method of a null object reference.
at omoixes10_fla::MainTimeline/EntFrame() when I move to next frame. I can not see what i did wrong. Can you please help me with my code? Do I have to remove tween before I move to next frame?
import flash.display.MovieClip;
import fl.transitions.Tween;
import fl.transitions.easing.*;
tick1.parent.removeChild(tick1);
wrong1.parent.removeChild(wrong1);
sentences2.buttonMode=true;
sentences1.buttonMode=true;
Piece1_mc.buttonMode=true;
var my_x:int=stage.stageWidth
var my_y:int=stage.stageHeight
var myWidth:int=0-my_x;
var myHeight:int=0-my_y;
var boundArea:Rectangle=new Rectangle(my_x, my_y, myWidth ,myHeight);
var spin:Tween=new Tween(Piece1_mc, "rotation",Elastic.easeInOut,0,360,5,true);
spin.stop();
sentences2.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
function fl_MouseClickHandler(event:MouseEvent):void
{
snoopy.gotoAndPlay(2);
addChild(tick1);
addChild(wrong1);
sentences2.removeEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
sentences1.removeEventListener(MouseEvent.CLICK, fl_MouseClickHandler_2);
spin.start();
spin.addEventListener(TweenEvent.MOTION_FINISH, onFinish);
function onFinish(e:TweenEvent):void {
e.target.yoyo();
{
Piece1_mc.addEventListener(MouseEvent.MOUSE_DOWN, DragP1);
function DragP1 (event:MouseEvent):void
{
Piece1_mc.startDrag();
Piece1_mc.startDrag(false,boundArea);
spin.stop();
}
stage.addEventListener(MouseEvent.MOUSE_UP, DropP1);
function DropP1(event:MouseEvent):void
{
Piece1_mc.stopDrag();
}
if(Targ1_mc.hitTestObject(Piece1_mc.Tar1_mc)) {
Piece1_mc.x=677;
Piece1_mc.y=48,10;
myTimer.start();
spin.stop();
}
}
}
sentences1.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler_2);
function fl_MouseClickHandler_2(event:MouseEvent):void
{
snoopy.gotoAndPlay(64);
}
var myTimer:Timer = new Timer(2000,1);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener (e:TimerEvent):void {
gotoAndStop(15);
if (Piece1_mc.parent)
{
Piece1_mc.parent.removeChild(Piece1_mc);
}if (tick1.parent)
{
tick1.parent.removeChild(tick1);
}
if (wrong1.parent)
{
wrong1.parent.removeChild(wrong1);
}
}
}
So the first problem was adding your event listeners inside an enter frame which was not the right way to do since it will keep on adding event listeners at every frame.
Second, you should use a mouse move event listener as I've recommended before to track and test your hit test.
Thirdly, since you are rotating your MovieClip, and you want it to go back to its initial state, you should do :
Piece1_mc.rotation=0;
Hope this helps.

Labyrinth/maze game

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.

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.

AS3 Works but I get a ReferenceError: Error #1069 Property startDrag not found

I am trying to make a simple project when you click a button a draggable MovieClip is added to the stag and when you click it releases the MovieClip to the X/Y where you clicked, you can then pickup the MovieClip and drag it into a bin (MovieClip) where it destroys itself. The code is working great I can make multiple Movieclips with the button and they are all destroyed when I drag them in the bin however I don't like having "Error Codes".
import flash.events.MouseEvent;
var rubbish:my_mc = new my_mc();
btntest.addEventListener(MouseEvent.CLICK, makeRubbish);
function makeRubbish (event:MouseEvent):void {
addChild(rubbish);
rubbish.x = mouseX - 10;
rubbish.y = mouseY - 10;
rubbish.width = 50;
this.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
rubbish.buttonMode = true;
}
function stopDragging (event:MouseEvent):void {
rubbish.stopDrag()
event.target.addEventListener(MouseEvent.CLICK, startDragging);
rubbish.buttonMode = true;
if (event.target.hitTestObject(bin))
{
trace("hit");
event.target.name = "rubbish";
removeChild(getChildByName("rubbish"));
}
}
function startDragging (event:MouseEvent):void {
event.target.startDrag();
this.addEventListener(MouseEvent.CLICK, stopDragging);
}
Some Pointers:
The target property of an Event is not always what it seems. It actually refers to the current phase in the event bubbling process. Try using the currentTarget property.
I would also recommend tying the stopDragging method to the stage, as sometimes your mouse won't be over the drag as you're clicking.
I would use the MOUSE_UP event as opposed to a CLICK for standard dragging behaviour.
When dragging, keep a global reference to the drag in order to call the stopDrag method on the correct object.
Try This:
import flash.events.MouseEvent;
var rubbish:my_mc = new my_mc();
var dragging:my_mc;
btntest.addEventListener(MouseEvent.CLICK, makeRubbish);
function makeRubbish (event:MouseEvent):void {
addChild(rubbish);
rubbish.x = mouseX - 10;
rubbish.y = mouseY - 10;
rubbish.width = 50;
rubbish.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
rubbish.buttonMode = true;
}
function stopDragging (event:MouseEvent):void {
this.stage.removeEventListener(MouseEvent.MOUSE_UP, stopDragging);
if(dragging !== null){
dragging.stopDrag();
if (event.currentTarget.hitTestObject(bin)){
removeChild(dragging);
}
dragging = null;
}
}
function startDragging (event:MouseEvent):void {
dragging = event.currentTarget as my_mc;
dragging.startDrag();
this.stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
}

In Flash Actionscript 3.0 how do I create smooth keyboard controls for player movement?

I am a beginner in Flash Actionscript 3.0 programming. I am trying to create smooth keyboard controls for player movement in a game.
I'm currently using addEventListener(KeyboardEvent.KEY_DOWN) listening for a keyboard key press and then within the handler function moving a graphic by adding a number to its .x or .y property.
This creates a slow, sluggish jerk at the beginning. I know there's a smoother, more responsive way to do this but have no idea where to begin. Any help would be appreciated!
For smooth keys I would suggest using either a Timer or onEnterFrame to poll for keys often enough to get smooth controls. It will get the job done, but at a certain expense. If you've got the rest of the logic all fine, this should fit in ok:
var key:int = NaN;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPress,false,0,true);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyRelease,false,0,true);
this.addEventListener(Event.ENTER_FRAME,update,false,0,true);
function onKeyPress(event:KeyboardEvent):void {
key = event.keyCode;
event.stopPropagation();
}
function onKeyRelease(event:KeyboardEvent):void {
key = NaN;
event.stopPropagation();
}
function update(event:Event):void{
if(key) trace(key);
}
I make sure the event doesn't bubble by stopping it's propagation, and it's set on the stage which should be the topmost level, event wise. Also I'm using the key only the key is down, otherwise I ignore it in the enterFrame handler.
HTH,
George
Where are you placing the listener? Is it in the application, or in the sprite that is supposed to move? Does the sprite have the focus when you are pressing the key?
Also, in adding the event listener, are you using capture? That is, are you setting the 3rd argument to true, as in
addEventListener(KeyboardEvent.KEY_DOWN, yourHandler, true)
If you use capture, which is how you have to do it if the App itself is listening for the event, then you will get a certain amount of latency, and this latency will be greater the more complex the interface is. If those events have to work their way up a vast hierarchy, this could be noticeable. If there are many sprites, this can exacerbate the problem.
What you can do is have the sprite that has the focus dispatch a custom event which a controller class listens to for each sprite. The controller class will have a handler that moves the event.currentTarget however you plan to have it done.
Also read up about custom events and how to use the SystemManager to add and remove listeners dynamically: http://livedocs.adobe.com/flex/3/langref/index.html.
the most simplest example to this would be this.
here you have a controllable Ship class(Ship.as).
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.events.Event;
public class Ship extends MovieClip {
private var speedX;
private var speedY;
public function Ship() {
//constructor
stage.addEventListener(KeyboardEvent.KEY_DOWN ,keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP ,keyUp);
stage.addEventListener(Event.ENTER_FRAME, update);
}
public function keyDown(e:KeyboardEvent) {
if(e.keyCode == 37) {
speedX = -5;
}
if(e.keyCode == 38) {
speedY = -5;
}
if(e.keyCode == 39) {
speedX = 5;
}
if(e.keyCode == 40) {
speedY = 5;
}
}
public function keyUp(e:KeyboardEvent) {
if(e.keyCode == 37 || e.keyCode == 39) {
speedX = 0;
}
if(e.keyCode == 38 || e.keyCode == 40) {
speedY = 0;
}
}
public function update(e:Event) {
x += speedX;
y += speedY;
}
}