我正在尝试让我的名为“turret”的子类从父类“Game”访问变量“leftArrow”和“rightArrow”,以便炮塔可以旋转。代码正在编译,但由于某种原因,它没有识别父变量的值的变化。这是父类:
package
{
import flash.display.MovieClip;
import flash.events.*;
public class Game extends MovieClip
{
// variables etc
public var leftArrow, rightArrow;
public function Game()
{
// add an event listener to spawn a new ship every frame
addEventListener(Event.ENTER_FRAME, loop);
addEventListener(KeyboardEvent.KEY_DOWN,keyPressedDown);
addEventListener(KeyboardEvent.KEY_DOWN,keyPressedUp);
}
function keyPressedDown(event:KeyboardEvent)
{
if (event.keyCode == 37) // left arrow
{
leftArrow = true;
}
if (event.keyCode == 39) // right arrow
{
rightArrow = true;
}
}
function keyPressedUp(event:KeyboardEvent)
{
if (event.keyCode == 37) // left arrow
{
leftArrow = false;
}
if (event.keyCode == 39) // right arrow
{
rightArrow = false;
}
}
function loop(e:Event)
{
// only spawn a ship if there are less than 10 already on screen
if (numChildren < 10)
{
// make a new instance of the Ship class
var s = new Ship();
// add the ship to the display list
addChild(s);
// position and rotate the ship
s.x = Math.random() * stage.stageWidth;
s.y = Math.random() * stage.stageHeight;
s.rotation = Math.random() * 360;
}
}
}
}
这是儿童班:
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.utils.getTimer;
public class Turret extends MovieClip
{
public function Turret()
{
addEventListener(Event.ENTER_FRAME, update);
}
function update(e:Event)
{
// make the turret move with key presses
if (MovieClip(parent).leftArrow)
{
trace("Made it here");
this.rotation += 5;
}
if (MovieClip(parent).rightArrow)
{
this.rotation += 5;
}
}
}
}
答案 0 :(得分:0)
问题可能与您的想法不同。键盘事件不会转到任何显示对象,而是转到被识别为焦点下的交互式对象的事件。虽然使用鼠标更简单,但键盘有点棘手。这就是为什么它是订阅键盘事件阶段的好动作,因为stage是所有显示树的根源,冒泡的键盘事件肯定会通过它:
public function Game()
{
if (stage) onStage();
else addEventListener(Event.ADDED_TO_STAGE, onStage);
}
private function onStage(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, onStage);
// add an event listener to spawn a new ship every frame
addEventListener(Event.ENTER_FRAME, loop);
stage.addEventListener(KeyboardEvent.KEY_UP, keyPressedUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);
}