Ошибка башни и пули AS3

Я боролся с as3 и флеш-игрой, которую я пытаюсь сделать. Вроде все хорошо, но пуля все равно застряла внутри пушки. Когда я использую свою мышь для стрельбы, вместо того, чтобы выйти на локацию, она просто застревает внутри пушки:

Получил 3 документа as3 и один флэш-документ:

Ships.as

package{

import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Point;

public class Ship extends Sprite{

private var speed:int;
private var target:Point;

function Ship(){
    speed=2+Math.random()*5;
    //trace("Made a Ship!");
    //set the target for the ships
    target = new Point(Math.random()*500, Math.random()*500);
    //target.x = Math.random()*500;
    //target.y = Math.random()*500;
    //addEventListener(Event.ENTER_FRAME, update);
}
function update(){
    //Set the ships to point the target
    var dx = target.x - x;
    var dy = target.y - y;
    var angle = Math.atan2(dy, dx)/Math.PI*180;
    rotation = angle;
    x=x+Math.cos(rotation/180*Math.PI)*speed;
    y=y+Math.sin(rotation/180*Math.PI)*speed;
    //New target
    var hyp = Math.sqrt((dx*dx)+(dy*dy));   
    if(hyp < 5){
    target.x = Math.random()*500;
    target.y = Math.random()*500;
    }
}

}
}

Игра.как

package{

import flash.display.MovieClip;
import flash.events.Event;

public class Game extends MovieClip{

    var ships:Array;

    public function Game(){
        trace("Made that game!");
        addEventListener(Event.ENTER_FRAME, loop);
        //set up the ship array
        ships = new Array();
    }
    function loop(e:Event){
        if(numChildren<10){
        var s = new Ship();
        addChild(s);

        s.x = Math.random()*stage.stageWidth;
        s.y = Math.random()*stage.stageHeight;
        s.rotation = Math.random()*360;

        //Add the ship to the list of ships
        ships.push(s);


        }
        //Make a for loop to iterate through all the ship
        for(var count=0; count<ships.length; count++){
            ships[count].update();
            //Add a new for loop to go through all the bullets


                }


            }


        }
    }
}

}

Башня.as

package{

import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;

    public class Turret extends MovieClip{

        //Properties goes here
        var shotCooldown:int;
        var bullets:Array;
        const MAX_COOLDOWN = 10;

    public function Turret(){

        //Set the Shot Cooldown
        shotCooldown = MAX_COOLDOWN;
        bullets = new Array();
        addEventListener(Event.ENTER_FRAME, update);
        addEventListener(Event.ADDED_TO_STAGE, initialise);
    }

    function initialise(e:Event)
    {
        stage.addEventListener(MouseEvent.CLICK, fire);
    }

    function fire(m:MouseEvent)
    {
        //If we are allowed to shoot
        if(shotCooldown<=0)
        {

            //Reset the Shot Cooldown
            shotCooldown=MAX_COOLDOWN;
        //Spawn a Bullet
        var b = new Bullet();

        b.rotation = rotation;
        b.x = x;
        b.y = y;
        //Add the bullet to the list of bullets
        bullets.push(b);
        parent.addChild(b);
        play();
        }
    }

    function update(e:Event)
    {
        //Reduce the Shot Cooldown by 1
        //shotCooldown=shotCooldown-1;
        //shotCooldown-=1;
        shotCooldown--;
        if(parent != null)
        {
        var dx = parent.mouseX - x;
        var dy = parent.mouseY - y;
        var angle = Math.atan2(dy, dx) / Math.PI * 180;
        rotation = angle;
        }
    }

}

}

person user3276442    schedule 05.02.2014    source источник


Ответы (2)


Они застряли на месте, может быть, потому, что вы их вообще не двигаете? Если да, то, пожалуйста, покажите мне, где. Попробуйте добавить к событию ввода кадра турели следующий код:

for (var a:int = 0; bullets.length > a ; a++)
{
    var temp:MovieClip;
    temp = bullets[a] as Bullet;

    var vel:Point = new Point();
    vel.x = temp.target.x-temp.x;
    vel.y = temp.target.y-temp.y;
    vel.normalize(4);

    temp.x += vel.x;
    temp.y += vel.y;
}

И создайте as-файл для класса Bullet и добавьте следующее:

package
{

   import flash.geom.Point;

   public class Bullet extends MovieClip 
   {

      public var target:Point = new Point();

       public function Bullet()
       {
           target.x = stage.mouseX;
           target.y = stage.mouseY;
       }

   }
}
person Community    schedule 05.02.2014
comment
Измените 4 в нормализации, чтобы настроить скорость, которая вам нравится. - person ; 06.02.2014
comment
Извини, приятель, забыл прокомментировать мой класс пули as3. Вот он: package{ import flash.display.Sprite; импортировать flash.events.Event; public class Bullet extends Sprite{ //Свойства private var speed:int; публичная функция Bullet () { скорость = 10; } function update(){ // Восстанавливаем быстродействующее значение mot x=x+Math.cos(rotation/180*Math.PI)*speed; y=y+Math.sin(вращение/180*Math.PI)*скорость; // Удаляем пулю, когда она за пределами экрана if(x‹0 || x›500 || y‹0 || y›500){ // Убираем пулю с экрана parent.removeChild(this); } } } } - person user3276442; 06.02.2014
comment
Я проверил ваш код, и он работал нормально, проблема в том, что вы не вызываете функцию обновления, попробуйте добавить прослушиватель событий ввода кадра в класс пули и вызвать в нем обновление. - person ; 06.02.2014

В классе Turret пули добавляются на сцену и массив, но не обновляются каждый кадр, как корабли. См. собственный комментарий об обновлении пуль!

person meps    schedule 05.02.2014