AS3 hitTestObject is not working - actionscript-3

I was making flash that moving a circle on my keyboard and creating a flash that hit the wall.
But method 'hitTestObject' is not working...
Hou to solve this ploblem?
import flash.events.KeyboardEvent;
import flash.events.Event;
stage.addEventListener(KeyboardEvent.KEY_DOWN,atKeydown);
stage.addEventListener(KeyboardEvent.KEY_UP,atKeyup);
function atKeydown(e :KeyboardEvent) :void
{
if(e.keyCode == 38) stage.addEventListener(Event.ENTER_FRAME,enterYUp);
if(e.keyCode == 40) stage.addEventListener(Event.ENTER_FRAME,enterYDown);
if(e.keyCode == 37) stage.addEventListener(Event.ENTER_FRAME,enterXLeft);
if(e.keyCode == 39) stage.addEventListener(Event.ENTER_FRAME,enterXRight);
}
function atKeyup(e :KeyboardEvent) :void
{
if(e.keyCode == 38) stage.removeEventListener(Event.ENTER_FRAME,enterYUp);
if(e.keyCode == 40) stage.removeEventListener(Event.ENTER_FRAME,enterYDown);
if(e.keyCode == 37) stage.removeEventListener(Event.ENTER_FRAME,enterXLeft);
if(e.keyCode == 39) stage.removeEventListener(Event.ENTER_FRAME,enterXRight);
}
function enterYUp(e :Event) :void
{
ball.y -= 10;
}
function enterYDown(e :Event) :void
{
ball.y += 10;
}
function enterXLeft(e :Event) :void
{
ball.x -= 10;
}
function enterXRight(e :Event) :void
{
ball.x += 10;
}
if(ball.hitTestObject(wall) == true) trace("!!!!");

function enterYUp(e :Event) :void
{
var bool = checkHit("y", -10); // each frame checks for a hit, returns a Boolean (see the function below)
carryOut(bool, "y", -10); // the movement is carried out based on the Boolean
}
function enterYDown(e :Event) :void
{
var bool = checkHit("y", +10); // you can send the "y" property, and where it wants to go.
carryOut(bool, "y", +10);
}
function enterXLeft(e :Event) :void
{
var bool = checkHit("x", -10);
carryOut(bool, "x", -10);
}
function enterXRight(e :Event) :void
{
var bool = checkHit("x", +10);
carryOut(bool, "x", -10);
}
function checkHit(_prop, _num):Boolean
{
// This single function will run every frame, comparing the balls 'predicted position'
if((ball[_prop] + _num) <= _numCheck)
{
// i might use hitTestPoint instead, but I hate using hitTestObject... it can act weird sometimes.
return true;
}
else
{
return false;
}
}
function carryOut(bool, _prop,_num):void
{
if(bool)
{
trace("hit");
}
else
{
// if the Boolean returned false
// ball[_prop] is ball.x or ball.y depending on if you sent "x" or "y".
// it will ADD the _num you sent, so adding -10 is the same as subtracting.
ball[_prop] += _num;
}
}

Related

How to add score when collecting things (Actionscript 3 Adobe Animate)?

How to create an incremented score after he pickup the rubbish? I am very new on this thing and need help on coding.
My code below is on a separated .as file (movieclip).
As you can see, there are codes for when the player hittestobject, the "rubbish" will go away but how to apply a new code for score to that specific function? so the score will be incremented each time he pick up the rubbish.
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class mazeClass extends MovieClip {
var mouseUp:Boolean = false;
var mouseDown:Boolean = false;
var mouseLeft:Boolean = false;
var mouseRight:Boolean = false;
var speed:Number = 5;
public function mazeClass() {
// constructor codea
stage.addEventListener(KeyboardEvent.KEY_DOWN, CheckDownKeys);
stage.addEventListener(KeyboardEvent.KEY_UP, CheckUpKeys);
stage.addEventListener(Event.ENTER_FRAME, updatePos);
}
private function CheckDownKeys(e:KeyboardEvent){
if(e.keyCode == Keyboard.UP){
mouseUp =true;
}
if(e.keyCode == Keyboard.DOWN){
mouseDown =true;
}
if(e.keyCode == Keyboard.LEFT){
mouseLeft =true;
}
if(e.keyCode == Keyboard.RIGHT){
mouseRight =true;
}
}
private function CheckUpKeys(e:KeyboardEvent){
if(e.keyCode == Keyboard.UP){
mouseUp =false;
}
if(e.keyCode == Keyboard.DOWN){
mouseDown =false;
}
if(e.keyCode == Keyboard.LEFT){
mouseLeft =false;
}
if(e.keyCode == Keyboard.RIGHT){
mouseRight =false;
}
}
private function updatePos(e:Event){
if(mouseUp == true){
if(!wall.hitTestPoint(jacob.x,jacob.y-22, true)){
jacob.y -= speed;
}
}
if(mouseDown == true){
if(!wall.hitTestPoint(jacob.x, jacob.y+22, true)){
jacob.y += speed;
}
}
if(mouseLeft == true){
if(!wall.hitTestPoint(jacob.x-22, jacob.y, true)){
jacob.x -= speed;
}
}
if(mouseRight == true){
if(!wall.hitTestPoint(jacob.x+22, jacob.y, true)){
jacob.x += speed;
}
}
if(jacob.hitTestObject(a1)){
a1.x = a1.y = -1000;
_root.score = 0;
_root.score++;
score.text = _root.score;
}
if(jacob.hitTestObject(a2)){
a2.x = a2.y = -1000;
}
if(jacob.hitTestObject(a3)){
a3.x = a3.y = -1000;
}
if(jacob.hitTestObject(a4)){
a4.x = a4.y = -1000;
}
}
}
}

Trying to add keyboard events to a child movieclip I call to the stage in code

So this is my first semester in school coding and right now I'm trying to make a little 2D game with a character who I need to move up and down.
So far, I've been able to create a titlescreen and then when you click start it goes to the next screen, where my main character is.
I add him to the stage manually through the code, and then I tried to make him move up down left and right with the arrow keys but he only appears, and does not move.
This is my code so far
package lib.fly
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class FlyGame extends MovieClip
{
public var mainCharacter:MovieClip;
public var vx:Number;
public var vy:Number;
public function FlyGame()
{
trace ("Initiate");
init();
}
private function init():void
{
vx = 0;
vy = 0;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveAround);
stage.addEventListener(KeyboardEvent.KEY_UP, dontMove);
//var dx:Number = speed* Math.cos(angle);
//var dy:Number = speed* Math.sin(angle);
trace ("Keyboard Event Listeners");
}
private function moveAround(event:KeyboardEvent):void
{
trace ("Actual Keyboard Events");
if (event.keyCode == Keyboard.LEFT)
{
vx = -5;
}
else if (event.keyCode == Keyboard.RIGHT)
{
vx = 5;
}
else if (event.keyCode == Keyboard.UP)
{
vy = - 5;
}
else if (event.keyCode == Keyboard.DOWN)
{
vy = 5;
}
}
private function dontMove(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
vx = 0;
}
else if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
vy = 0;
}
}
public function onEnterFrame(event:Event):void
{
mainCharacter = new BoyFlying();
mainCharacter.x = 20;
mainCharacter.y = 150;
mainCharacter.x += vx;
mainCharacter.y += vy;
addChild(mainCharacter);
}
}
}
The output produces the trace statements up until my "Actual Keyboard Events"
Sorry, I'm brand new to this so any help would be appreciated. Thank you for your time
Try this logic below and see if it helps your program to work as expected...
Adjust function init()
private function init():void
{
vx = vy = 0; //chain them since same value
mainCharacter = new BoyFlying(); //create once here and control in other functions
mainCharacter.x = 20;
mainCharacter.y = 150;
mainCharacter.addEventListener(Event.ENTER_FRAME, onEnterFrame);
addChild(mainCharacter);
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveAround);
//stage.addEventListener(KeyboardEvent.KEY_UP, dontMove); //what is it good for?
trace ("added... Keyboard Event Listeners");
//var dx:Number = speed* Math.cos(angle);
//var dy:Number = speed* Math.sin(angle);
}
Adjust function moveAround()
private function moveAround(event:KeyboardEvent):void
{
trace ("Actual Keyboard Events");
if (event.keyCode == Keyboard.LEFT)
{ vx -= 5; }
if (event.keyCode == Keyboard.RIGHT)
{ vx += 5; }
if (event.keyCode == Keyboard.UP)
{ vy -= 5; }
if (event.keyCode == Keyboard.DOWN)
{ vy += 5; }
}
Adjust function onEnterFrame()
public function onEnterFrame(event:Event):void
{
//# no need for += here since function moveAround() changes these vx and vy values on key press
//# infact your character could be moved (x/y) just by keyboard event instead of per FPS screen update (eg: not with EnterFrame)
mainCharacter.x = vx;
mainCharacter.y = vy;
}

Actionscript 3 returns Error #1009

I am creating a shooting game. I have encountered a problem with my code when I decided to create a method to remove the missile after reaching the top of the stage. I can run the program without any issues only I have realize that the missile was not remove away from the stage, if I hold the shooting button. However, if I tap the shooting button, the missile will removed away with this error #1009 printing out of the output.
Is there any solution to fix the problem?
Here's is the error after the missile flew to the top of the stage with debugging enabled:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Missle/destroyMissle()[E:\Experiment\ExperimentProject\Missle.as:39]
at main/checkMissleOffScreen()[E:\Experiment\ExperimentProject\main.as:63]
at main/eventUpdated()[E:\Experiment\ExperimentProject\main.as:51]
Here's the main's class:
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
/**
* ...
* #author test
*/
public class main extends MovieClip
{
//Objects
public var rect:MovieClip;
public var missle:Missle;
//Array
private var missleArray:Array;
//Keyboard section
var leftKeyIsDown:Boolean;
var rightKeyIsDown:Boolean;
var upKeyIsDown:Boolean;
var downKeyIsDown:Boolean;
var spaceKeyIsDown:Boolean;
//Speed
var characterSpeed:Number = 15;
//Main constructor
public function main()
{
//Array initializer
missleArray = new Array();
missle = new Missle();
//Update events listeners.
stage.addEventListener(Event.ENTER_FRAME, eventUpdated);
//Update keyboard events listeners
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUnpressed);
}
//Events functions
//This functions updated everytime the object is move
private function eventUpdated(e:Event):void
{
playerMoving();
playerClampMoving();
checkMissleOffScreen();
}
private function checkMissleOffScreen():void
{
for (var i = 0; i < missleArray.length; i++ )
{
var currentMissle:Missle = missleArray[i];
if (currentMissle.y < 0)
{
missleArray.splice(i, 1);
missle.destroyMissle();
}
}
}
private function playerClampMoving():void
{
if (rect.x < 0)
{
rect.x = 0;
}
if (rect.x > stage.stageWidth - rect.width)
{
rect.x = stage.stageWidth - rect.width;
}
if (rect.y < 0)
{
rect.y = 0;
}
if (rect.y > stage.stageHeight - rect.height)
{
rect.y = stage.stageHeight - rect.height;
}
}
private function playerMoving():void
{
if (leftKeyIsDown == true)
{
rect.x -= characterSpeed;
}
if (rightKeyIsDown == true)
{
rect.x += characterSpeed;
}
if (upKeyIsDown == true)
{
rect.y -= characterSpeed;
}
if (downKeyIsDown == true)
{
rect.y += characterSpeed;
}
if (spaceKeyIsDown == true)
{
shootingMissle();
}
}
private function shootingMissle():void
{
missle = new Missle();
missle.x = rect.x + (rect.width / 2);
missle.y = rect.y;
missleArray.push(missle);
trace(missleArray.length);
stage.addChild(missle);
}
//Keyboard functions
//Check to see whether the user releases the keyboard
private function keyUnpressed(e:KeyboardEvent):void
{
if (e.keyCode == 37)
{
leftKeyIsDown = false;
}
if (e.keyCode == 39)
{
rightKeyIsDown = false;
}
if (e.keyCode == 40)
{
downKeyIsDown = false;
}
if (e.keyCode == 38)
{
upKeyIsDown = false;
}
if (e.keyCode == 32)
{
spaceKeyIsDown = false;
}
}
//Check to see whether the user presses the keyboard
private function keyPressed(e:KeyboardEvent):void
{
if (e.keyCode == 37)
{
leftKeyIsDown = true;
}
if (e.keyCode == 39)
{
rightKeyIsDown = true;
}
if (e.keyCode == 40)
{
downKeyIsDown = true;
}
if (e.keyCode == 38)
{
upKeyIsDown = true;
}
if (e.keyCode == 32)
{
spaceKeyIsDown = true;
}
}
}
}
Here's the Missle's Class:
package
{
import flash.display.Sprite;
import flash.events.Event;
/**
* ...
* #author test
*/
public class Missle extends Sprite
{
public function Missle()
{
addEventListener(Event.ADDED_TO_STAGE, onAdd);
}
private function onAdd(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAdd);
//Objects are on the stage
init();
}
private function init():void
{
addEventListener(Event.ENTER_FRAME, missleLaunch);
}
private function missleLaunch(e:Event):void
{
this.y -= 15;
}
public function destroyMissle():void
{
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME, missleLaunch);
}
}
}
Try this:
public function destroyMissle():void
{
if(parent !== null) parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME, missleLaunch);
}
It is a possibility that you were calling .destroyMissile() more than once meaning parent would be null because you've removed it from the stage and it has no parent.

Animation stop actionscript 3.0 tick

So, I have this game and I want the player to move, so I use a tick method when the key is down it creates 2 event listeners, a keyup listener and a tick.The keyup listener removes its self and removes the tick.The tick contains the movement and where I presumed the animation.
Here is my code:
// For every frame //
import flash.events.Event;
import flash.events.TouchEvent;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
var gravity = 0.6;
var floor = 410;
jordan1.y = floor;
jordan1.speedY = floor;
jordan1.impulsion = 10;
var onFloor:Boolean = false;
var keyRight:Boolean = false;
stage.addChild(jordan1);
stage.addChild(leftwall1);
stage.addChild(finish1);
stage.addChildAt(abovedoor, 0);
stage.addChild(left);
stage.addChild(right);
stage.addChild(jump);
addEventListener(Event.ENTER_FRAME, enters);
function enters(e:Event) {
jordan1.speedY += gravity;
jordan1.y += jordan1.speedY
if(jordan1.y > floor) {
jordan1.speedY = 0;
jordan1.y = floor;
onFloor = true;
if(keyRight == true) {
jordan1.gotoAndPlay(7);
}
if(keyRight == false) {
jordan1.gotoAndStop(1);
}
}
}
function stageup(e:MouseEvent) {
removeEventListener(Event.ENTER_FRAME,tickleft);
removeEventListener(Event.ENTER_FRAME,tickright);
removeEventListener(MouseEvent.MOUSE_UP, stageup);
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, stagedown);
function stagedown(e:MouseEvent) {
stage.addEventListener(MouseEvent.MOUSE_UP, stageup);
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, jumpkey);
function jumpkey(e:KeyboardEvent) {
if(e.keyCode == Keyboard.SPACE) {
if(onFloor == true)
{
jordan1.speedY=-jordan1.impulsion;
onFloor = false;
jordan1.gotoAndStop(2);
}
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, leftkey);
function leftkey(e:KeyboardEvent) {
if(e.keyCode == Keyboard.LEFT) {
addEventListener(Event.ENTER_FRAME, leftkeytick);
stage.addEventListener(KeyboardEvent.KEY_UP, leftkeydown);
}
}
function leftkeydown(e:KeyboardEvent) {
removeEventListener(Event.ENTER_FRAME, leftkeytick);
stage.removeEventListener(KeyboardEvent.KEY_UP, leftkeydown);
}
function leftkeytick(e:Event) {
jordan1.x-=10;
if(onFloor == true) {
jordan1.gotoAndStop(3);
}
if(onFloor == false) {
jordan1.gotoAndStop(6);
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, rightkey);
function rightkey(e:KeyboardEvent) {
if(e.keyCode == Keyboard.RIGHT) {
keyRight == true;
addEventListener(Event.ENTER_FRAME, rightkeytick);
stage.addEventListener(KeyboardEvent.KEY_UP, rightkeydown);
}
}
function rightkeydown(e:KeyboardEvent) {
removeEventListener(Event.ENTER_FRAME, rightkeytick);
keyRight == false;
stage.removeEventListener(KeyboardEvent.KEY_UP, rightkeydown);
}
function rightkeytick(e:Event) {
jordan1.x+=10;
if(onFloor == true) {
jordan1.gotoAndPlay(7);
}
if(onFloor == false) {
jordan1.gotoAndStop(5);
}
}
// Just for this frame //
leftwall1.addEventListener(Event.ENTER_FRAME, leftwall1hit);
function leftwall1hit(e:Event) {
if(leftwall1.hitTestObject(jordan1)) {
jordan1.x +=10;
}
}
abovedoor.addEventListener(Event.ENTER_FRAME, abovedoorhit);
function abovedoorhit(e:Event) {
if(abovedoor.hitTestObject(jordan1)) {
jordan1.x-=10;
}
}
jordan1.addEventListener(Event.ENTER_FRAME, finish1hit);
function finish1hit(e:Event) {
if(jordan1.x > 960) {
gotoAndStop(67);
}
}
So, when I test it and put the keydown it goestoandstops at 7, instead of playing.Please help! Thank you!
Your goto shouldn't be in your tick, or they will be executed each frame. Which explain why it's staying on frame 7.
Instead put them in your KEY_DOWNlistener :
animated = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, rightkey);
function rightkey(e:KeyboardEvent) {
if(e.keyCode == Keyboard.RIGHT) {
if(onFloor == true && !animated) {
jordan1.gotoAndPlay(7);
}
if(onFloor == false && !animated) {
jordan1.gotoAndStop(5);
}
animated = true;
addEventListener(Event.ENTER_FRAME, rightkeytick);
stage.addEventListener(KeyboardEvent.KEY_UP, rightkeydown);
}
}
function rightkeydown(e:KeyboardEvent) {
animated = false;
removeEventListener(Event.ENTER_FRAME, rightkeytick);
stage.removeEventListener(KeyboardEvent.KEY_UP, rightkeydown);
}
function rightkeytick(e:Event) {
jordan1.x+=10;
}
But you shouldn't use a tick function with a keydown event.
KEY_DOWNis called each frame while you're pressing the/a key.
If you can't change your logic (which is not good for what you want to achieve) you could flag your handlers.
By having a boolean for each key you're listening to.
And then in your tick, do what you need to do depending on what keys are down.
keyRight = false;
keyLeft = false;
//... same for all your keys.
// or you could store them in one object for a more dynamic solution.
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
stage.addEventListener(Event.ENTER_FRAME,tick);
function keyDown(e:KeyboardEvent){
if(e.keyCode === Keyboard.RIGHT && !keyRight){
keyRight = true;
}
else if(e.keyCode === Keyboard.LEFT && !keyLeft){
keyLeft = true;
}
//... same for all your keys.
}
function keyUp(e:KeyboardEvent){
if(e.keyCode === Keyboard.RIGHT){
keyRight = false;
}
else if(e.keyCode === Keyboard.LEFT){
keyLeft = false;
}
//... same for all your keys.
}
function tick(e:Event){
if(keyRight) jordan1.x += 10;
if(keyLeft) jordan1.x -= 10;
//... etc for all your keys.
}
This other question cover the subject of multiple KEY_DOWN pretty well.

Some Problems with my AS3 code

Some troubles to make my new flash game(i used AS3,CS5.5):
I just try to make my character(hatt) walk and jump, but I can't make it at the same time, well, idk how... Furthermore, I don't know how make my character recognize the ground.
And at last this thing here:
"Scene 1, Layer 'hatt', Frame 1, Line 6 Warning: 1090: 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)."
Plz help me and give some hints plz... Thanks.
Here's the code:
var grav:Number = 10;
var jumping:Boolean = false;
var jumpPow:Number = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(Event.ENTER_FRAME, update);
function onKeyDown(evt:KeyboardEvent):void
{
if (evt.keyCode == Keyboard.UP)
{
if (jumping != true)
{
jumpPow = -25;
jumping = true;
}
}
}
function update(evt:Event):void
{
if (jumping)
{
hatt.y += jumpPow;
jumpPow += grav;
if (hatt.y >= stage.stageHeight)
{
jumping = false;
hatt.y = stage.stageHeight;
}
}
}
stage.addEventListener (KeyboardEvent.KEY_DOWN, myFunction) ;
function myFunction (event: KeyboardEvent){
if(event.keyCode == Keyboard.LEFT) {
hatt.x -= 5
}
if(event.keyCode == Keyboard.RIGHT) {
hatt.x += 5
}
}
remove this line:
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
remove function onKeyDown:
function onKeyDown(evt:KeyboardEvent):void
{
if (evt.keyCode == Keyboard.UP)
{
if (jumping != true)
{
jumpPow = -25;
jumping = true;
}
}
}
replace myFunction with this:
function myFunction (event: KeyboardEvent)
{
if(event.keyCode == Keyboard.LEFT)
hatt.x -= 5;
if(event.keyCode == Keyboard.RIGHT)
hatt.x += 5;
if(event.keyCode == Keyboard.UP && jumping != true)
{
jumpPow = -25;
jumping = true;
}
}