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;
}
}
Related
Having multiple movieclips being able to move around on a grid, once dragging it, it seems to duplicate and the 'original' remains in place.
What causes it to duplicate in my code?
import flash.display.MovieClip
[SWF(width = 1300, height = 1000)]
var tileSize: int = 100;
var cols: int = stage.stageWidth / tileSize;
var rows: int = stage.stageHeight / tileSize;
var grid: Sprite = Sprite(addChild(new Sprite()));
grid.graphics.lineStyle(0, 0x000000, 0);
var i: int = 0;
for (i = 1; i < cols; i++) {
var posX: Number = i * tileSize
grid.graphics.moveTo(posX, 0);
grid.graphics.lineTo(posX, stage.stageHeight);
}
for (i = 1; i < rows; i++) {
var posY: Number = i * tileSize
grid.graphics.moveTo(0, posY);
grid.graphics.lineTo(stage.stageWidth, posY);
var ball: the_ball = new the_ball();
addChild(ball);
ball.x = tileSize * 5;
ball.y = tileSize * 5;
ball.buttonMode = true;
ball.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
function onDown(evt: MouseEvent): void {
addEventListener(Event.ENTER_FRAME, onRunSnapping);
}
function onRunSnapping(evt: Event): void {
ball.x = Math.round(mouseX / tileSize) * tileSize;
ball.y = Math.round(mouseY / tileSize) * tileSize;
}
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
function onUp(evt: MouseEvent): void {
removeEventListener(Event.ENTER_FRAME, onRunSnapping);
}
}
It's not duplicating, there are just many movieclips stacked on top of each other.
You add a new ball for each row you add on the exact same position.
I dont know how you want the balls to be distributed, but try to replace
ball.y = tileSize * 5; with ball.y = posY; to see what im talking about.
I am attempting to add a new movie clip into the next frame of my shooter game.
I am using Actionscript 3.0
To give a basis of what I need help with for my assessment. When the score =50, switch to the next frame. And this is where I would like to add a new type of movie clip for the user to shoot!
Here is the code I have so far.
FRAME 1
//Tate's open screen
stop(); //makes the screen wait for events
paraBtn.addEventListener(MouseEvent.CLICK, playClicked); //this line is making your button an mouse click event
function playClicked(evt: MouseEvent): void { // now we are calling the event from this function and telling it to go to the next frame we labelled play
gotoAndStop("frame2");
// All rights of this music goes towards the makers of the game "Risk of Rain" which was made by Hapoo Games
}
FRAME 2 (Where the game actually starts)
stop();
// This plays the sound when left click is used
var spitSound: Sound = new Sound();
spitSound.load(new URLRequest("gunSound.mp3"));
//This plays the gameover sound when your lives reach 0
var overSound: Sound = new Sound();
overSound.load(new URLRequest("Gameover.mp3"));
//This plays the sound when you are hit
var etSound: Sound = new Sound();
etSound.load(new URLRequest("Urgh.mp3"));
//This sets the lives and points.
stage.addEventListener(MouseEvent.MOUSE_MOVE, aimTurret);
var points: Number = 0;
var lives: Number = 3;
var target: MovieClip;
var _health: uint = 100;
initialiseCursor();
//This variable stops the multiple errors with the move objects and bullets and range to stop compiling.
var Gameover: Boolean = false;
//This aims the turrent to where you mouse is on the screen
function aimTurret(evt: Event): void {
if (Gameover == false) {
gun.rotation = getAngle(gun.x, gun.y, mouseX, mouseY);
var distance: Number = getDistance(gun.x, gun.y, mouseX, mouseY);
var adjDistance: Number = distance / 12 - 7;
}
}
function getAngle(x1: Number, y1: Number, x2: Number, y2: Number): Number {
var radians: Number = Math.atan2(y2 - y1, x2 - x1);
return rad2deg(radians);
}
function getDistance(x1: Number, y1: Number, x2: Number, y2: Number): Number {
var dx: Number = x2 - x1;
var dy: Number = y2 - y1;
return Math.sqrt(dx * dx + dy * dy);
}
function rad2deg(rad: Number): Number {
return rad * (180 / Math.PI);
}
//Starts lives and shows text next to the numbers
function initialiseCursor(): void {
Mouse.hide();
target = new Target();
target.x = mouseX;
target.y = mouseY;
target.mouseEnabled = false;
addChild(target);
stage.addEventListener(MouseEvent.MOUSE_MOVE, targetMove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, targetDown);
stage.addEventListener(MouseEvent.MOUSE_UP, targetUp);
livesdisplay.text = String(lives) + " Lives Left";
pointsdisplay.text = String(points) + " Points";
}
function targetMove(evt: MouseEvent): void {
target.x = this.mouseX;
target.y = this.mouseY;
}
function targetDown(evt: MouseEvent): void {
target.gotoAndStop(2);
}
function targetUp(evt: MouseEvent): void {
target.gotoAndStop(1);
}
//Starts bullets and speed of bullets, also addding new arrays for baddies
var gunLength: uint = 90;
var bullets: Array = new Array();
var bulletSpeed: uint = 20;
var baddies: Array = new Array();
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
function fireGun(evt: MouseEvent) {
if (Gameover == false) {
var bullet: Bullet = new Bullet();
bullet.rotation = gun.rotation;
bullet.x = gun.x + Math.cos(deg2rad(gun.rotation)) * gunLength;
bullet.y = gun.y + Math.sin(deg2rad(gun.rotation)) * gunLength;
addChild(bullet);
bullets.push(bullet);
spitSound.play();
}
}
function deg2rad(deg: Number): Number {
return deg * (Math.PI / 180);
}
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
function moveObjects(evt: Event): void {
if (Gameover == false) {
moveBullets();
moveBaddies();
}
}
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);
}
}
}
// This is the start of the timer
var timer: Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
timer.start();
// Adding army men on a timer and only from the top side
function addBaddie(evt: TimerEvent): void {
var baddie: Baddie = new Baddie();
var side: Number = Math.ceil(Math.random() * 1);
if (side == 1) {
baddie.x = Math.random() * stage.stageWidth;
baddie.y = -baddie.height;
}
baddie.angle = getAngle(baddie.x, baddie.y, gun.x, gun.y);
baddie.speed = 7;
addChild(baddie);
baddies.push(baddie);
}
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(gun.x, gun.y, true)) {
removeChild(baddies[i]);
baddies.splice(i, 1);
loseLife();
//If baddie was removed then we don’t check for bullet hits
} else {
checkForHit(baddies[i]);
}
}
}
function checkForHit(baddie: Baddie): void {
for (var i: int = 0; i < bullets.length; i++) {
if (baddie.hitTestPoint(bullets[i].x, bullets[i].y, true)) {
removeChild(baddie);
points++;
if (points == 50) {
gotoAndStop("frame3")
}
pointsdisplay.text = String(points) + " Points";
baddies.splice(baddies.indexOf(baddie), 1);
}
}
}
// Keeping track of lost lives and when hitting 0 doing to frame four, also displaying "Lose life!"
function loseLife(): void {
etSound.play();
lives--;
if (lives == 0) {
Gameover = true;
overSound.play();
gotoAndStop("frame4")
}
livesdisplay.text = String(lives) + " Lives Left";
trace("Lose Life!");
}
FRAME 3 (This is where I need help, to add another movie clip) (I have made one for the frame named, "BaddieRed" With the Linkage being "Baddiered"
stop();
// The code from frame2 carries over and works the same in this frame
FRAME 4 (This is the screen where it's gameover)
stop();
timer.stop();
// User need to close by pressing the close button
//And restart the game manually
Is this what you're trying to achieve? Something like...
function addBaddie(evt: TimerEvent): void
{
var baddie : MovieClip;
if (points < 50) { var bad1: Baddie = new Baddie(); baddie = bad1; }
if (points >= 50) { var bad2 : Baddiered = new Baddiered(); baddie = bad2; }
var side: Number = Math.ceil(Math.random() * 1);
if (side == 1)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y -= baddie.height;
}
baddie.angle = getAngle(baddie.x, baddie.y, gun.x, gun.y);
baddie.speed = 7;
addChild(baddie);
baddies.push(baddie);
}
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();
I had some AS3 code that I wanted to move to the timeline rather than having an external file but it's not working at all, whereas it did in the .as file:
public class EnemyShip extends MovieClip
{
var speed:Number;
var shot = new ShotSound();
function EnemyShip()
{
this.x = 800;
this.y = Math.random() * 275 + 75;
speed = Math.random()*5 + 9;
addEventListener("enterFrame", enterFrame);
addEventListener(MouseEvent.MOUSE_DOWN, mouseShoot);
}
function enterFrame(e:Event)
{
this.x -= speed;
if(this.x < -100)
{
removeEventListener("enterFrame", enterFrame);
Main.gameLayer.removeChild(this);
}
}
function kill()
{
var explosion = new Explosion();
Main.gameLayer.addChild(explosion);
explosion.x = this.x;
explosion.y = this.y;
removeEventListener("enterFrame", enterFrame);
Main.gameLayer.removeChild(this);
Main.updateScore(1);
shot.play();
}
function mouseShoot(event:MouseEvent)
{
kill();
}
That is the code and I've tried adapting it to work in the timeline but nothing happens. I tried adding the code to the EnemyShip movieclip itself as well as adding it to the in game scene but it doesn't work. Any suggestions?
This is a bit sad, using an external class is a cleaner way to do things, but you decide.
Remove every class wrapper and put this code on the first frame of your symbol:
var speed:Number;
var shot = new ShotSound();
this.x = 800;
this.y = Math.random() * 275 + 75;
speed = Math.random()*5 + 9;
addEventListener("enterFrame", enterFrame);
addEventListener(MouseEvent.MOUSE_DOWN, mouseShoot);
function enterFrame(e:Event)
{
this.x -= speed;
if(this.x < -100)
{
removeEventListener("enterFrame", enterFrame);
Main.gameLayer.removeChild(this);
}
}
function kill()
{
var explosion = new Explosion();
Main.gameLayer.addChild(explosion);
explosion.x = this.x;
explosion.y = this.y;
removeEventListener("enterFrame", enterFrame);
Main.gameLayer.removeChild(this);
Main.updateScore(1);
shot.play();
}
function mouseShoot(event:MouseEvent)
{
kill();
}
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);