i'm about to finish my project for University. But I'm stuck with the hittestobject.
var Player: gun = new gun();
Player.x = mouseX;
Player.y = mouseY;
addChild(Player);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mousemove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, shoot);
stage.addEventListener(MouseEvent.MOUSE_UP, release_shoot);
function mousemove(e: MouseEvent): void
{
Player.x = mouseX + 200;
Player.y = mouseY + 35;
}
function shoot(event: Event): void
{
var Bullet: bullet = new bullet();
/*var explosion:explo1 = new explo1(); */
Bullet.x = Player.x;
Bullet.y = Player.y;
/* explosion.x = Player.x;
explosion.y = Player.y;*/
Player.rotationX = 5;
Player.rotationY = 5;
addChild(Bullet);
/* addChild(explosion);*/
Bullet.addEventListener(Event.ENTER_FRAME, moveBullet);
}
function release_shoot(event: Event): void
{
var explosion: explo1 = new explo1();
Player.rotationX = -5;
Player.rotationY = -5;
}
function moveBullet(e: Event): void
{
e.target.y -= 12;
e.target.x -= 96;
if (e.target.y <= -200 || e.target.x <= -200)
{
e.target.removeEventListener(Event.ENTER_FRAME, moveBullet);
removeChild(MovieClip(e.target));
}
}
function goesside_1(event: Event): void
{
mc_target.x -= 2;
if (mc_target.x < -20)
mc_target.x = 550;
}
mc_target.addEventListener(Event.ENTER_FRAME, goesside_1);
function targeting(event: Event): void
{
var bullet: MovieClip = MovieClip(event.target);
if (bullet.hitTestObject(mc_target))
{
mc_burst.x = mc_target.x;
mc_burst.y = mc_target.y;
mc_burst.gotoAndPlay(2);
mc_target.x = 200;
mc_target.removeEventListener(Event.ENTER_FRAME, targeting);
mc_target.x = 200;
trace("targerting");
}
else if (mc_target.x > 550)
bullet.removeEventListener(Event.ENTER_FRAME, targeting);
else
bullet.y -= 12;
bullet.x -= 96;
}
The bullet is going in the Target without any doubt, I see it haha... But won't replace mc_target with mc_burst.
EDIT
This is the working code I used for anyone who's interested:
var Player:gun = new gun();
Player.x = mouseX;
Player.y = mouseY;
addChild(Player);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mousemove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, shoot);
stage.addEventListener(MouseEvent.MOUSE_UP, release_shoot);
function mousemove(e:MouseEvent):void{
Player.x = mouseX + 200;
Player.y = mouseY + 35;
}
function shoot(event:Event):void{
var bullet1:bullet = new bullet();
/*var explosion:explo1 = new explo1(); */
bullet1.x = Player.x;
bullet1.y = Player.y;
/* explosion.x = Player.x;
explosion.y = Player.y;*/
Player.rotationX = 5;
Player.rotationY = 5;
addChild(bullet1);
/* addChild(explosion);*/
bullet1.addEventListener(Event.ENTER_FRAME, targeting);
}
function release_shoot(event:Event):void{
var explosion:explo1 = new explo1();
Player.rotationX =- 5;
Player.rotationY =- 5;
}
function movebullet(e:Event):void{
e.target.y -= 12;
e.target.x -=96;/*When the function is called the targets Y position will be subract by 40 pixels every frame, this makes the movieclip move up. The target is the Bullet movieclip.*/
if(e.target.y <= -200 && e.target.x <= -200 ){
e.target.removeEventListener(Event.ENTER_FRAME, movebullet);
removeChild(MovieClip(e.target));
}
}
function goesside_1(event:Event):void {
mc_target.x -= 2;
if (mc_target.x < -20)
mc_target.x = 550;
}
mc_target.addEventListener(Event.ENTER_FRAME, goesside_1);
function targeting(event:Event):void {
var bullet1:MovieClip = MovieClip(event.target);
if (bullet1.hitTestObject(mc_target)){
mc_burst.x = mc_target.y;
mc_burst.y = mc_target.x;
mc_burst.gotoAndPlay(2);
mc_target.x = 200;
mc_target.removeEventListener(Event.ENTER_FRAME, targeting);
mc_target.x = 200;
trace("targerting");
}
else if (mc_target.x > 550){
bullet1.removeEventListener(Event.ENTER_FRAME, targeting);
}
else{
bullet1.y -= 12;
bullet1.x -= 96;}
}
// REPLACING CURSOR BY A SIGHT //
import flash.ui.Mouse;
Mouse.hide();
var myCursor:sight = new sight();
myCursor.visible = false;
function init()
{
addChild(myCursor);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
stage.addEventListener(MouseEvent.ROLL_OVER, mouseLeaveHandler);
stage.addEventListener(MouseEvent.ROLL_OUT, mouseMoveHandler);
}
function mouseMoveHandler(evt:MouseEvent):void
{
myCursor.visible = true;
myCursor.x = evt.stageX + 10;
myCursor.y = evt.stageY + 10;
}
function mouseLeaveHandler(evt:Event):void
{
myCursor.visible = false;
}
init();
Assuming the code you've posted is everything, the issue is that the targeting method is never called.
Seems like you want to add it as a handler for the enter frame event (as you are removing a listener to that end inside the method)
eg.
bulletInstance.addEventListener(Event.ENTER_FRAME, targeting);
That said, looking at your code, you're going to want to combine your move and targeting functions (you don't want to keep collision checking after you've removed the bullet in your moveBullet function) - or at least remove the targeting enter frame listener when you remove the button from the screen.
Possibly something like this:
function removeBullet(b:MovieClip):void {
b.removeEventListener(Event.ENTER_FRAME, moveBullet);
removeChild(MovieClip(b));
}
function moveBullet(e:Event):void {
var bullet:MovieClip = MovieClip(event.target);
bullet.y -= 12;
bullet.x -= 96;
if(bullet.y <= -200 || bullet.x <= -200 ){
removeBullet(bullet);
}
if (bullet.hitTestObject(mc_target)){
mc_burst.x = mc_target.x;
mc_burst.y = mc_target.y;
mc_burst.gotoAndPlay(2);
mc_target.x = 200;
removeBullet(bullet);
trace("targerting");
} else if (mc_target.x > 550){
removeBullet(bullet);
}
}
If you have many bullets, you'll probably want to have just one enter frame handler, and iterate through each bullet there - instead of having a separate enter frame handler for each bullet.
Also, I'm surprised you are not getting errors, because you have ambiguous naming going on. You have a class called bullet, but then you create vars called bullet as well. Standard practice in AS3 is the give your class names a capitol first letter, and your instance names a lowercase first letter. I'd recommend you do this to avoid errors and ambiguous code.
I would like to thanks BadFeelingAboutThis for his fast help here.
So for people who want to use my code, go head it works now
var Player:gun = new gun();
Player.x = mouseX;
Player.y = mouseY;
addChild(Player);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mousemove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, shoot);
stage.addEventListener(MouseEvent.MOUSE_UP, release_shoot);
function mousemove(e:MouseEvent):void{
Player.x = mouseX + 200;
Player.y = mouseY + 35;
}
function shoot(event:Event):void{
var bullet1:bullet = new bullet();
/*var explosion:explo1 = new explo1(); */
bullet1.x = Player.x;
bullet1.y = Player.y;
/* explosion.x = Player.x;
explosion.y = Player.y;*/
Player.rotationX = 5;
Player.rotationY = 5;
addChild(bullet1);
/* addChild(explosion);*/
bullet1.addEventListener(Event.ENTER_FRAME, targeting);
}
function release_shoot(event:Event):void{
var explosion:explo1 = new explo1();
Player.rotationX =- 5;
Player.rotationY =- 5;
}
function movebullet(e:Event):void{
e.target.y -= 12;
e.target.x -=96;/*When the function is called the targets Y position will be subract by 40 pixels every frame, this makes the movieclip move up. The target is the Bullet movieclip.*/
if(e.target.y <= -200 && e.target.x <= -200 ){
e.target.removeEventListener(Event.ENTER_FRAME, movebullet);
removeChild(MovieClip(e.target));
}
}
function goesside_1(event:Event):void {
mc_target.x -= 2;
if (mc_target.x < -20)
mc_target.x = 550;
}
mc_target.addEventListener(Event.ENTER_FRAME, goesside_1);
function targeting(event:Event):void {
var bullet1:MovieClip = MovieClip(event.target);
if (bullet1.hitTestObject(mc_target)){
mc_burst.x = mc_target.y;
mc_burst.y = mc_target.x;
mc_burst.gotoAndPlay(2);
mc_target.x = 200;
mc_target.removeEventListener(Event.ENTER_FRAME, targeting);
mc_target.x = 200;
trace("targerting");
}
else if (mc_target.x > 550){
bullet1.removeEventListener(Event.ENTER_FRAME, targeting);
}
else{
bullet1.y -= 12;
bullet1.x -= 96;}
}
// REPLACING CURSOR BY A SIGHT //
import flash.ui.Mouse;
Mouse.hide();
var myCursor:sight = new sight();
myCursor.visible = false;
function init()
{
addChild(myCursor);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
stage.addEventListener(MouseEvent.ROLL_OVER, mouseLeaveHandler);
stage.addEventListener(MouseEvent.ROLL_OUT, mouseMoveHandler);
}
function mouseMoveHandler(evt:MouseEvent):void
{
myCursor.visible = true;
myCursor.x = evt.stageX + 10;
myCursor.y = evt.stageY + 10;
}
function mouseLeaveHandler(evt:Event):void
{
myCursor.visible = false;
}
init();
Related
Wondering if you guys can help me. I've used online tutorials to create the following.
I am working on a small flash project and I've hit a wall. Basically, I've got 3 scenes. A home page, and 2 games. My home page and one of the games are programmed on the timeline within an actions layer. The third game is applied to a Main.as. The problem is that I want to apply a button called home to the Flappy game, but since I've used the .as file for this code, I'm unsure how to do it.
Basically, my question is "How do I add a button to the "Flappy" Scene? Each time i try to do it and run a test, It's playing the Flappy Game over the Scene 1.
Main.as ("Flappy" Scene3)
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; //used for ENTER_FRAME event
//import flash.events.MouseEvent;
public class Main extends MovieClip{
//These are all of the constants used.
const gravity:Number = 1.5; //gravity of the game. How fast ball falls
const dist_btw_obstacles:Number = 300; //distance between two obstacles
const ob_speed:Number = 8; //speed of the obstacle
const jump_force:Number = 15; //force with which it jumps
//variables
var player:Player = new Player();
var lastob:Obstacle = new Obstacle(); //varible to store the last obstacle in the obstacle array
var obstacles:Array = new Array(); //an array to store all the obstacles
var yspeed:Number = 0; //A variable representing the vertical speed of the bird
var score:Number = 0; //A variable representing the score
public function Main(){
init();
}
function init():void {
//initialize all the variables
player = new Player();
lastob = new Obstacle();
obstacles = new Array();
yspeed = 0;
score = 0;
//add player to center of the stage the stage
player.x = stage.stageWidth/2;
player.y = stage.stageHeight/2;
addChild(player);
//create 3 obstacles ()
createObstacle();
createObstacle();
createObstacle();
//Add EnterFrame EventListeners (which is called every frame) and KeyBoard EventListeners
addEventListener(Event.ENTER_FRAME,onEnterFrameHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, key_up);
}
private function key_up(event:KeyboardEvent){
if(event.keyCode == Keyboard.SPACE){
//If space is pressed then make the bird
yspeed = -jump_force;
}
}
function restart(){
if(contains(player))
removeChild(player);
for(var i:int = 0; i < obstacles.length; ++i){
if(contains(obstacles[i]) && obstacles[i] != null)
removeChild(obstacles[i]);
obstacles[i] = null;
}
obstacles.slice(0);
init();
}
function onEnterFrameHandler(event:Event){
//update player
yspeed += gravity;
player.y += yspeed;
//restart if the player touches the ground
if(player.y + player.height/2 > stage.stageHeight){
restart();
}
//Don't allow the sheep to go above the screen
if(player.y - player.height/2 < 0){
player.y = player.height/2;
}
//update obstacles
for(var i:int = 0;i<obstacles.length;++i){
updateObstacle(i);
}
//display the score
scoretxt.text = String(score);
}
//This functions update the obstacle
function updateObstacle(i:int){
var ob:Obstacle = obstacles[i];
if(ob == null)
return;
ob.x -= ob_speed;
if(ob.x < -ob.width){
//if an obstacle reaches left of the stage then change its position to the back of the last obstacle
changeObstacle(ob);
}
//If the bird hits an obstacle then restart the game
if(ob.hitTestPoint(player.x + player.width/2,player.y + player.height/2,true)
|| ob.hitTestPoint(player.x + player.width/2,player.y - player.height/2,true)
|| ob.hitTestPoint(player.x - player.width/2,player.y + player.height/2,true)
|| ob.hitTestPoint(player.x - player.width/2,player.y - player.height/2,true)){
restart();
}
//If the bird got through the obstacle without hitting it then increase the score
if((player.x - player.width/2 > ob.x + ob.width/2) && !ob.covered){
++score;
ob.covered = true;
}
}
//This function changes the position of the obstacle such that it will be the last obstacle and it also randomizes its y position
function changeObstacle(ob:Obstacle){
ob.x = lastob.x + dist_btw_obstacles;
ob.y = 100+Math.random()*(stage.stageHeight-200);
lastob = ob;
ob.covered = false;
}
//this function creates an obstacle
function createObstacle(){
var ob:Obstacle = new Obstacle();
if(lastob.x == 0)
ob.x = 800;
else
ob.x = lastob.x + dist_btw_obstacles;
ob.y = 100+Math.random()*(stage.stageHeight-200);
addChild(ob);
obstacles.push(ob);
lastob = ob;
}
}
}
Here is the code for my main page called "Scenery" (Scene 1) which is in an actions layer of timeline.
stop();
import flash.events.MouseEvent;
sun1.addEventListener(MouseEvent.CLICK,cloudy);
function cloudy (e:MouseEvent){
cloud1.x = cloud1.x + 10;
cloud2.x = cloud2.x - 10;
}
pong_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
function mouseDownHandler(event:MouseEvent):void {
gotoAndStop(1, "SheepyPong");
}
dodge_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler3);
function mouseDownHandler3(event:MouseEvent):void {
gotoAndStop(1, "Flappy");
}
This is my code for a very simple "SheepyPong" (Scene2) game which is linked to from front page:
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var velocityX:Number = 5;
var velocityY:Number = 5;
movieClip_1.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
movieClip_1.y -= 5;
}
if (downPressed)
{
movieClip_1.y += 5;
}
sheep.x += velocityX;
sheep.y += velocityY;
if(sheep.y + sheep.height/2 > stage.stageHeight || sheep.y - sheep.height/2 < 0){
velocityY *= -1
}
if(sheep.hitTestObject(AI) || sheep.hitTestObject(movieClip_1)){
velocityX *= -1;
}
if (sheep.x < 0) {
score2.text = (int(score2.text) +1).toString();
sheep.x = 275;
sheep.y = 200;
velocityX *= -1;
}
if (sheep.x > stage.stageWidth) {
score1.text = (int(score1.text) +1).toString();
sheep.x = 275;
sheep.y = 200;
velocityX *= -1;
}
AI.y = sheep.y;
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = true;
break;
}
case Keyboard.DOWN:
{
downPressed = true;
break;
}
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = false;
break;
}
case Keyboard.DOWN:
{
downPressed = false;
break;
}
}//end of switch
}//end of function
home_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler1);
function mouseDownHandler1(event:MouseEvent):void {
gotoAndStop(1, "Scenery");
}
I'm also getting this error in output when I run it. It's not actually affecting the outpu
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main/onEnterFrameHandler()[/Users/mynamehere/Documents/Game/Main.as:91]
//This is line 91 in the Main.as file:
scoretxt.text = String(score);
Here is my code so far, I am trying to create a top down car game and here is the code I have so far, I am currently trying to get the cars to loop but I am struggling to find a way to do it, please try and help me out with the code or point me in the right direction if you can please and thank you in advance
import flashx.textLayout.utils.CharacterUtil;
var result:Number = Math.random() * 100
var randomX:Number = Math.random() * stage.stageWidth
var background = new Background;
var char = new Char();
var car1 = new Car1();
var car2 = new Car2();
var car3 = new Car3();
var car4 = new Car4();
car1.x = Math.random()* stage.stageWidth;
car2.x = Math.random()* stage.stageWidth;
car3.x = Math.random()* stage.stageWidth;
car4.x = Math.random()* stage.stageWidth;
background.x = 200;
char.x = 700/2;
car1.y = -0;
car2.y = -150;
car3.y = -300;
car4.y = -450;
background.y = 200;
char.y = 450;
addChild(background);
addChild(char);
addChild(car1);
addChild(car2);
addChild(car3);
addChild(car4);
char.gotoAndStop("car");
addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);
function fl_EnterFrameHandler(event:Event):void
{
car1.y +=12;
car2.y +=12;
car3.y +=12;
car4.y +=12;
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_PressKeyToMove);
function fl_PressKeyToMove(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.RIGHT:
{
char.x += 15;
if (char.hitTestObject(barrier1))
{
char.x -=15 ;
}
break;
}
case Keyboard.LEFT:
{
char.x -= 15;
if (char.hitTestObject(barrier2))
{
char.x +=15 ;
}
break;
}
}
}
stage.addEventListener(Event.ENTER_FRAME, detectCollision);
function detectCollision(event:Event) {
if(char.hitTestObject(car1))
{
char.gotoAndStop("boom");
}
if(char.hitTestObject(car2))
{
char.gotoAndStop("boom");
}
if(char.hitTestObject(car3))
{
char.gotoAndStop("boom");
}
if(char.hitTestObject(car4))
{
char.gotoAndStop("boom");
}
}
If you're trying to get cars to reposition to the top of the screen as #onekidney guessed, you could easily do so by using the % operator:
function fl_EnterFrameHandler(event:Event):void
{
car1.y = (car1.y + 12) % stage.stageHeight;
car2.y = (car2.y + 12) % stage.stageHeight;
car3.y = (car3.y + 12) % stage.stageHeight;
car4.y = (car4.y + 12) % stage.stageHeight;
}
You can read more about the modulo operator in the documentation
I want to make a top down strategy game in as3, and I want the user to be able to mark multiple movieclips with the mouse, like in operating systems where ju press the mouse button down and then drag the mouse, and it will create a rectangle. How do you do that in as3?
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
var sp : Sprite = new Sprite();
var p1 : Point = new Point();
var p2 : Point = new Point();
function onDown(e:MouseEvent) : void {
p1.x = mouseX;
p1.y = mouseY;
addEventListener(Event.ENTER_FRAME, onMove);
}
function onMove(e:Event) : void {
p2.x = mouseX;
p2.y = mouseY;
draw();
}
function onUp(e:MouseEvent) : void {
removeEventListener(Event.ENTER_FRAME, onMove);
stage.removeChild(sp);
}
function draw() : void {
sp.graphics.clear();
p2.x = p2.x - p1.x;
p2.y = p2.y - p1.y;
sp.graphics.lineStyle(1, 0x0000FF);
sp.graphics.beginFill(0xC2C2C2, 0.2);
sp.graphics.drawRect(p1.x, p1.y, p2.x, p2.y);
stage.addChild(sp);
}
Hope this helps...
You can do like that (copy and paste the following code into your Actions panel):
var s:Shape = new Shape();
s.graphics.beginFill(0xC2C2C2, 0.2);
s.graphics.lineStyle(0, 0x666666);
s.graphics.drawRect(0, 0, 100, 100);
function mouseDownHandler(e:MouseEvent):void {
addChild(s);
s.x = e.stageX;
s.y = e.stageY;
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
function enterFrameHandler(e:Event):void {
s.scaleX = (mouseX - s.x) / 100;
s.scaleY = (mouseY - s.y) / 100;
}
function mouseUpHandler(e:MouseEvent):void {
removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
removeChild(s);
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
It's nice to have a simple selection box, but how about some selectable objects?
Have a look at what I've got, it's quite simple, and most of the code is for the visuals.
// Add 100 green circles.
var objects:Vector.<Sprite> = new Vector.<Sprite>();
for(var i:int = 0; i < 100; ++i){
var object:Sprite = new Sprite();
object.x = Math.random() * stage.stageWidth;
object.y = Math.random() * stage.stageHeight;
object.graphics.lineStyle(2, 0x00FF00);
object.graphics.beginFill(0x00FF00, 0.5);
object.graphics.drawCircle(0,0,15);
object.graphics.endFill();
objects.push(object);
addChild(object);
}
// Main variables we'll be using.
var startPos:Point = new Point();
var selection:Rectangle = new Rectangle();
var isSelecting:Boolean = false;
// Mouse listeners.
stage.addEventListener(MouseEvent.MOUSE_DOWN, mDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mUp);
function mDown(e:MouseEvent):void {
startPos.x = stage.mouseX;
startPos.y = stage.mouseY;
isSelecting = true;
}
function mUp(e:MouseEvent):void {
isSelecting = false;
}
// Main loop; check if we're intersecting with any of the sprites; if so render them yellow.
stage.addEventListener(Event.ENTER_FRAME, loop);
function loop(e:Event):void {
graphics.clear();
if(isSelecting) {
selection = new Rectangle(startPos.x, startPos.y, stage.mouseX - startPos.x, stage.mouseY - startPos.y);
normalize(selection);
graphics.lineStyle(2, 0xFF0000);
graphics.beginFill(0xFF0000, 0.5);
graphics.drawRect(selection.x, selection.y, selection.width, selection.height);
graphics.endFill();
for (var j:int = 0; j < objects.length; ++j) {
var object:Sprite = objects[j];
if(selection.intersects(object.getBounds(this))){
object.graphics.clear();
object.graphics.lineStyle(2, 0xFFCC00);
object.graphics.beginFill(0xFFCC00, 0.5);
object.graphics.drawCircle(0,0,15);
object.graphics.endFill();
}
}
}
}
// Intersection requires positive values.
function normalize(rect:Rectangle):void {
if (rect.width < 0) {
rect.width = -rect.width;
rect.x -= rect.width;
}
if (rect.height < 0) {
rect.height = -rect.height;
rect.y -= rect.height;
}
}
I'm having major issues with this one error
//Obligitory Stop
stop();
//Imports
import flash.events.Event;
import flash.events.KeyboardEvent;
import fl.motion.easing.Back;
import flash.events.MouseEvent;
import flash.accessibility.Accessibility;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.display.MovieClip;
//Variables
var bulletSpeed:uint = 20;
var scoreData:int;
var bullets:Array = new Array();
var killCounter:int;
var baddieCounter:int;
var currentLevel:int = 1;
var baddieDamage:int;
var energyCost:int;
var target:MovieClip;
var baddies:Array = new Array();
var timer:Timer = new Timer(1);
var baddieSpeed:int;
var score:int;
var levelKR:int;
var level1KR:int = 10;
var level2KR:int = 25;
var level3KR:int = 50;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var Baddie:MovieClip
var mySound:Sound = new ShootSFX();
//Level Atributes set
if (currentLevel == 1)
{
baddieSpeed = 2;
baddieDamage = 20;
timer.delay = 4000;
levelKR = level1KR;
bulletSpeed = 10;
energyCost = 50;
var energyTimer:Timer = new Timer(50);
var healthTimer:Timer = new Timer(1000);
}
//Event Listeners
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
rbDash.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
//Timers Start
timer.start();
energyTimer.start();
healthTimer.start();
//Initialize score
Score.text = String("Level "+currentLevel+" - begin!");
//load score data
score = scoreData;
//Checks Kill Counter
checkKillCounter();
//Shoot gun on space
function fireGun(evt:KeyboardEvent)
{
if (evt.keyCode == Keyboard.SPACE)
{
bullet.x = rbDash.x;
bullet.y = rbDash.y + 50;
addChild(bullet);
bullets.push(bullet);
}
}
//Move Objects
function moveObjects(evt:Event):void
{
moveBullets();
moveBaddies();
}
//Move bullets
function moveBullets():void
{
for (var i:int = 0; i < bullets.length; i++)
{
var dx = Math.cos(deg2rad(bullets[i].rotation)) * bulletSpeed;
var dy = Math.sin(deg2rad(bullets[i].rotation)) * bulletSpeed;
bullets[i].x += dx;
bullets[i].y += dy;
if (bullets[i].x <-bullets[i].width
|| bullets[i].x > stage.stageWidth + bullets[i].width
|| bullets[i].y < -bullets[i].width
|| bullets[i].y > stage.stageHeight + bullets[i].width)
{
removeChild(bullets[i]);
bullets.splice(i, 1);
}
}
}
//Spawns Enemy
function addBaddie(evt:TimerEvent):void
{
updateScore(25);
var baddie:Baddie = new Baddie();
var side:Number = Math.ceil(Math.random() * 4);
if (side == 1)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y = - baddie.height;
}
else if (side == 2)
{
baddie.x = stage.stageWidth + baddie.width;
baddie.y = Math.random() * stage.stageHeight;
}
else if (side == 3)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y = stage.stageHeight + baddie.height;
}
else if (side == 4)
{
baddie.x = - baddie.width;
baddie.y = Math.random() * stage.stageHeight;
}
baddie.speed = baddieSpeed;
addChild(baddie);
baddies.push(baddie);
baddieCounter += 1;
if (baddieCounter == levelKR)
{
timer.stop();
}
}
//Moves Enemy
function moveBaddies():void
{
for (var i:int = 0; i < baddies.length; i++)
{
var dx = Math.cos(deg2rad(baddies[i].angle)) * baddies[i].speed;
var dy = Math.sin(deg2rad(baddies[i].angle)) * baddies[i].speed;
baddies[i].x += dx;
baddies[i].y += dy;
if (baddies[i].hitTestPoint(rbDash.x,rbDash.y,true))
{
removeChild(baddies[i]);
baddies.splice(i, 1);
//HealthBar.gotoAndStop(HealthBar.currentFrame + baddieDamage);
killCounter += 1;
checkKillCounter();
//if (HealthBar.currentFrame == 100)
{
gotoAndStop(5);
}
}
else
{
checkForHit(baddies[i]);
}
}
}
//Hit detection
function checkForHit(baddie:Baddie):void {//Level 1, Layer 'Actions', Frame 1, Line 166 1046: Type was not found or was not a compile-time constant: Baddie.
for (var i:int = 0; i < bullets.length; i++)
{
if (baddie.hitTestPoint(bullets[i].x,bullets[i].y,true))
{
removeChild(baddie);
removeChild(bullets[i]);
baddies.splice(baddie.indexOf(baddie), 1);
bullets.splice(bullets[i]);
updateScore(100);
killCounter += 1;
checkKillCounter();
}
}
}
//Updates score
function updateScore(points:int):void
{
score += points;
Score.text = String("Points: "+score);
}
//stops timers
function timerStop():void
{
timer.stop();
energyTimer.stop();
healthTimer.stop();
}
//Y axis movement
//totaly not a code snippet
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
rbDash.y -= 5;
}
if (downPressed)
{
rbDash.y += 5;
}
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP :
{
upPressed = true;
break;
};
case Keyboard.DOWN :
{
downPressed = true;
break;
}
}
};
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP :
{
upPressed = false;
break;
};
case Keyboard.DOWN :
{
downPressed = false;
break;
}
}
};
//makes the deg2rad work for the bullets/enemy
function deg2rad(degree)
{
return degree * (Math.PI / 180);//Had issues with "deg2rad" functions
}
//Removes listeners
function removeAllListeners():void
{
stage.removeEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.removeEventListener(Event.ENTER_FRAME, moveObjects);
timer.removeEventListener(TimerEvent.TIMER, addBaddie);
}
//Checks if level end
function checkKillCounter():void
{
EnemiesLeft.text = ("Enemies Left: "+String(levelKR - killCounter));
if (killCounter == levelKR)
{
shutdown();
gotoAndStop(3);
}
}
//Stops everything
function shutdown():void
{
timerStop();
removeAllListeners();
removeChild(target);
}
I get Level 1, Layer 'Actions', Frame 1, Line 166 1046: Type was not found or was not a compile-time constant: Baddie.
Thanks Guys
Im trying to get this done today so i can move on
Is Baddie a class that is in the default package? If not, you need to import it:
import packagename.Baddie;
If Baddie is a library symbol, make sure you've checked 'Export for ActionScript' and that the linkage name is correct. Also make sure that is is exported in frame 1, or at least before or on the frame that your code is on.
In you Library, right click on Baddie and choose "properties" and check "export for ActionScript". Now you can use Baddie as a class that extends MovieClip.
Sorry, I didn't notice this was already recommended. Basically, your error cannot find a Class named Baddie, hence why you need to specify the custom class through the Library instance.
Ok, let me start off by saying that this is my first AS3 project. I'm ok with Java, so OOP and inheritance aren't new to me.
I have literally spent hours sitting here and pondering why my code isn't working like I wanted it to.
I'm starting off with a turret trying to shoot a bullet. However, the bullet isn't being drawn onto the screen, even though the x and y coords are still changing.
The method where the bullet/projectile is created is called OnMouseClick.
Here's my code:
public class Main extends Sprite
{
public var projectileArr : Array = new Array(); //array which the projectile objects are stored
public var projCount : Number = 0; //projectile counter
public var curX:Number; //mouse coords
public var curY:Number;
private var tri1:Sprite = new Sprite();
private var tri1Height:Number = 50;
private var rect1:Sprite = new Sprite();
private var rect1W:Number = 2;
private var rect1H:Number = 10;
private var angle:Number = 0;
private var acceleration:Number = 0;
public var triSpeedX:Number = 0;
public var triSpeedY:Number = 0;
public var turretAngle:Number ;
//keyboard booleans
private var leftDown:Boolean = false, rightDown:Boolean = false, upDown:Boolean = false, downDown:Boolean = false;
public function Main():void
{
if (stage)
init();
else
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
//draw triangle
addChild(tri1);
tri1.graphics.lineStyle(1, 0xff00ff00);
tri1.graphics.beginFill(0xff0000);
tri1.graphics.moveTo(0, -tri1Height / 2)
tri1.graphics.lineTo(tri1Height / 3, +tri1Height / 2);
tri1.graphics.lineTo(-tri1Height / 3, +tri1Height / 2);
tri1.graphics.endFill();
tri1.x = 400;
tri1.y = 300;
//draw turret
addChild(rect1);
rect1.graphics.beginFill(0xFFFFFF);
rect1.graphics.moveTo(rect1W / 2, -rect1H);
rect1.graphics.lineTo(rect1W / 2, 0);
rect1.graphics.lineTo(-rect1W / 2, 0);
rect1.graphics.lineTo(-rect1W / 2, -rect1H);
rect1.graphics.endFill();
rect1.x = tri1.x;
rect1.y = tri1.y;
stage.addEventListener(KeyboardEvent.KEY_UP, onUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
stage.addEventListener(Event.ENTER_FRAME, Run);
stage.addEventListener(MouseEvent.MOUSE_MOVE, getMouseCoord);
stage.addEventListener(MouseEvent.MOUSE_DOWN, OnMouseClick);
}
//creation of projectile on click
public function OnMouseClick (e:MouseEvent):void
{
projectileArr[projCount] = new Projectile (rect1.x, rect1.y, turretAngle); //create a new projectile object
addChild(projectileArr [projCount]); //... then it doesn't display
projCount++;
trace ("BAM");
}
public function getMouseCoord(e:MouseEvent):void
{
curX = mouseX;
curY = mouseY;
}
public function onUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.LEFT)
leftDown = false;
else if (e.keyCode == Keyboard.RIGHT)
rightDown = false;
if (e.keyCode == Keyboard.UP)
upDown = false;
else if (e.keyCode == Keyboard.DOWN)
downDown = false;
}
public function onDown(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.LEFT)
leftDown = true;
else if (e.keyCode == Keyboard.RIGHT)
rightDown = true;
if (e.keyCode == Keyboard.UP)
upDown = true;
else if (e.keyCode == Keyboard.DOWN)
downDown = true;
}
public function addProjToScreen (projectile:Projectile) : void
{
addChild(projectile);
}
private function Run(e:Event):void
{
acceleration = 0; //resets acceleration back to 0 to limit speed
if (leftDown)
{
angle -= 5;
}
else if (rightDown)
{
angle += 5;
}
if (upDown)
{
acceleration += 3;
}
else if (downDown)
{
acceleration -= 3;
}
triSpeedX += acceleration * Math.cos(angle * Math.PI / 180);
triSpeedY += acceleration * Math.sin(angle * Math.PI / 180);
tri1.x += triSpeedX;
tri1.y += triSpeedY;
//borders
if (tri1.x < 0)
{
triSpeedX *= -.5;
tri1.x = 0 ;
}
if (tri1.x > 800 )
{
tri1.x = 800;
triSpeedX *= -.5;
}
if (tri1.y < 0)
{
triSpeedY *= -.5;
tri1.y = 0 ;
}
if (tri1.y > 600)
{
triSpeedY *= -.5;
tri1.y = 600;
}
//friction
triSpeedX *= 0.95
triSpeedY *= 0.95
rect1.x = tri1.x;
rect1.y = tri1.y;
var xCurDist:Number = curX - rect1.x;
var yCurDist:Number = curY - rect1.y;
turretAngle = Math.atan(yCurDist / xCurDist) * 180 / Math.PI ;
if (xCurDist < 0 )
{
turretAngle += 180;
}
if (xCurDist > 0 && yCurDist < 0 )
{
turretAngle += 360;
}
rect1.rotation= turretAngle + 90; // + 90 to account for the sprite originally pointing up, which is 270 degrees ccw
tri1.rotation = angle + 90;
for (var i:int = 0 ; i < projCount ; i ++)
{
projectileArr [i].move();
}
}
}
and the Projectile class:
public class Projectile extends MovieClip
{
private var projectile : Sprite = new Sprite();
private var speed: int = 10;
private var angle :Number;
private var xIncr: Number;
private var yIncr: Number;
public function Projectile(x:Number, y:Number, angle:Number)
{
this.x = x;
this.y = y;
this.angle = angle;
projectile.graphics.beginFill (0xFF0000);
projectile.graphics.drawCircle (x, y, 4);
projectile.graphics.endFill() ;
xIncr = speed * Math.cos (angle); // angle needs to be converted to radians
yIncr = speed * Math.sin (angle);
}
public function move () :void
{
trace (this.x + " " + this.y);
this.x += xIncr;
this.y += yIncr;
}
}
I just don't know what I'm missing... I'm calling addChild to all of my newly created objects, what else is there to do?
You are not adding the sprite projectile to the displaylist of Projectile in your constructor.
addChild(projectile);
Also you are doubling up on x and y co-ordinates in your projectile class. Rectify this by changing projectile.graphics.drawCircle (x, y, 4); to projectile.graphics.drawCircle (0, 0, 4);