将事件监听器添加到按钮

时间:2013-02-28 23:01:48

标签: actionscript-3 flash actionscript

我是Actionscript的新手,我正在创建一个简单的添加游戏,玩家将点击屏幕底部的数字1到9来解决添加问题。我应该在底部创建单独的按钮或动画片段吗?

如何向按钮/影片剪辑中添加事件侦听器,以便能够判断玩家是否单击了第二个按钮而不是屏幕上的其他按钮。谢谢!

Screenshot

2 个答案:

答案 0 :(得分:1)

我要做的是制作一个带有文本字段的影片剪辑。例如,我有一个影片剪辑(链接名称为NumClip)和一个名为numText的动态文本字段(确保嵌入数字或您需要的任何其他字符)。然后一个简单的for循环就可以了。

var maxNum:Number = 9;

for (var i:int = 1; i <= maxNum; i++)
{
    var clip:NumClip = new NumClip();
    clip.x = i * (clip.width + 5);
    clip.y = 50;
    clip.id = i;
    clip.numText.text = String(i);
    clip.addEventListener(MouseEvent.CLICK, numClick);
    addChild(clip);
}

function numClick(e:MouseEvent):void
{
    trace("You clicked number " + e.currentTarget.id);
}

我还没有测试过这段代码,但它对我来说很好看,应该做的诀窍

答案 1 :(得分:1)

非常类似于Ronnie的解决方案(我几乎完成了这个,所以不得不发布)并且经过测试:

import flash.display.MovieClip;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.events.MouseEvent;
import flash.text.TextFormat;

var buttonCount = 9;
var buttonSize = 50;

var button:MovieClip;
var label:TextField;

for (var i:int = 0; i < buttonCount; i ++)
{
    // Create a new MovieClip
    button = new MovieClip();

    // We'll use this in the event handler to identify which button was clicked
    button.id = i + 1;

    // Draw the background in the graphics prop of the MovieClip
    button.graphics.beginFill(0x00ff00, 1);
    button.graphics.drawRect(0, 0, buttonSize, buttonSize);

    // Add event listener
    button.addEventListener(MouseEvent.CLICK, this.clickHandler);

    // Position the button
    button.x = i * (buttonSize + 20); // Add some spacing
    button.y = stage.stageHeight - buttonSize - 10;

    // Add the button to the stage
    addChild(button);   

    // Create the label for the button
    label = new TextField();
    label.text = button.id.toString();
    label.selectable = false;
    label.multiline = false;
    label.autoSize = TextFieldAutoSize.LEFT;
    label.setTextFormat(new TextFormat('Arial', 12, 0, true));

    // Position the label in the centre of the button
    label.x = (buttonSize - label.width) / 2;
    label.y = (buttonSize - label.height) / 2;

    // Add the label to the button MovieClip
    button.addChild(label);
}

function clickHandler(event:MouseEvent):void
{
    trace("Button clicked:", event.currentTarget.id);
}