Flash 将hitTestPoint()与stage对象一起使用以创建对象边界
我试图在游戏中使用主舞台的高度和宽度为玩家对象创建一个由箭头键控制的边界。例如,一个测试点位于玩家对象边界框的上边缘,因此当玩家对象的头部接触舞台的上边缘时,玩家无法再向北移动。通过使用FlashStage编辑器,玩家对象被手动实例化到舞台的中心,因此它将在程序启动之前在中心启动 问题是,在程序开始时,我不能再使用箭头键上下移动播放器对象,但我仍然可以将其向左或向右移动。目的是允许玩家向北移动,直到玩家对象的头部接触到主舞台的顶部边缘。代码如下:Flash 将hitTestPoint()与stage对象一起使用以创建对象边界,flash,actionscript-3,controls,boundary,Flash,Actionscript 3,Controls,Boundary,我试图在游戏中使用主舞台的高度和宽度为玩家对象创建一个由箭头键控制的边界。例如,一个测试点位于玩家对象边界框的上边缘,因此当玩家对象的头部接触舞台的上边缘时,玩家无法再向北移动。通过使用FlashStage编辑器,玩家对象被手动实例化到舞台的中心,因此它将在程序启动之前在中心启动 问题是,在程序开始时,我不能再使用箭头键上下移动播放器对象,但我仍然可以将其向左或向右移动。目的是允许玩家向北移动,直到玩家对象的头部接触到主舞台的顶部边缘。代码如下: package { publi
package
{
public class Main_Playground extends MovieClip
{
var vx:int;
var vy:int;
public function Main_Playground()
{
init();
}
function init():void
{
//initialize variables
vx = 0;
vy = 0;
//Add event listeners
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
function onKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
vx = -5;
}
else if (event.keyCode == Keyboard.RIGHT)
{
vx = 5;
}
else if (event.keyCode == Keyboard.UP)
{
vy = -5;
}
else if (event.keyCode == Keyboard.DOWN)
{
vy = 5;
}
}
function onKeyUp(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
vx = 0;
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == Keyboard.UP)
{
vy = 0;
}
}
function onEnterFrame(event:Event):void
{
//Move the player
player.x += vx;
player.y += vy;
//determine top boundary
if (! stage.hitTestPoint(player.x, (player.y-(player.height/2)), true ) ){
player.y -= vy;
}
}
}
}
使用shape flag设置为true的stage对象将产生错误:测试在stage上渲染的任何实际像素是否命中该点(可能返回
false
,除非在可视stage区域之外的对象恰好位于指定的点)
当然,您可以将其设置为false
,然后再试一次(这会更好,但仍然存在一个问题,即您是针对舞台上渲染的所有内容而不是实际舞台区域的边界框进行测试的),但我是否可以建议一种不同的方法
根据舞台边界测试玩家的边界框更有效,特别是因为你的精灵可能比舞台小得多:
function onEnterFrame (ev:Event) : void {
player.x += vx;
player.y += vy;
var playerBounds:Rectangle = player.getBounds(stage);
if (playerBounds.left < 0 || playerBounds.right > stage.stageWidth) player.x -= vx;
if (playerBounds.top < 0 || playerBounds.bottom > stage.stageHeight) player.y -= vy;
}
函数一帧间(ev:事件):无效{
player.x+=vx;
player.y+=vy;
var playerBounds:Rectangle=player.getBounds(stage);
如果(playerBounds.left<0 | | playerBounds.right>stage.stageWidth)player.x-=vx;
如果(playerBounds.top<0 | | playerBounds.bottom>stage.stageHeight)player.y-=vy;
}
当然,在启动时,播放器必须位于可见的舞台区域内,您可能必须将焦点设置到舞台上,以确保捕获键盘事件。我已经成功地使用了其他方法,但我很好奇
hitTestPoint
是如何工作的。我已经将hitTestPoint
的第三个参数设置为false。玩家对象现在可以向北移动,但它不是停在舞台边缘,而是被一个与玩家对象高度相同的不可见障碍物阻挡。在hitTestPoint
的第二个参数中,我将player.height
除以4,但player对象向北移动时将离开舞台边界。正如我所说:hitTestPoint实际上是测试displayObject是否与舞台坐标相关的点相交。第三个参数指定是根据边界框(即,围绕属于对象的所有对象的矩形)还是实际像素进行测试。您可以在舞台上放置一个与可视区域大小完全相同的矩形,这样您的hitTest可能会运行一段时间。但是,由于您正在舞台上放置和移动玩家,因此将其移出可见区域也会更改边界框!最好不要在stage对象上使用hitTest。