所以我需要让元素跳跃。我有 6 个元素(项目)的数组。我需要让它们随机跳跃,但如果有任何项目跳跃,其他项目应该保留。
我有跳跃代码,位于 EnterFrame
对于 1 项,它工作正常 - 不停跳。
但是这里有一个问题,如果我尝试使用此函数一次(例如 MouseEvent.CLICK),项目会将项目的 y 减少 15px。如果我第二次使用这个函数,它会再次减少 y 15px。所以我需要启动这个函数 19 次才能完全跳转。
//whether or not the main guy is jumping
var mainJumping:Boolean = false;
//how quickly should the jump start off
var jumpSpeedLimit:int = 15;
//the current speed of the jump;
var jumpSpeed:Number = jumpSpeedLimit;
function updateItems(e:Event):void {
var j:Number = Math.round(Math.random()*5);
if(!mainJumping){
//then start jumping
mainJumping = true;
jumpSpeed = jumpSpeedLimit*-1;
item1[j].y += jumpSpeed;
} else {
//then continue jumping if already in the air
if(jumpSpeed < 0){
jumpSpeed *= 1 - jumpSpeedLimit/75;
if(jumpSpeed > -jumpSpeedLimit/5){
jumpSpeed *= -1;
}
}
if(jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit){
jumpSpeed *= 1 + jumpSpeedLimit/50;
}
item1.y += jumpSpeed;
//if main hits the floor, then stop jumping
//of course, we'll change this once we create the level
if(item1[j].y <= 450){
mainJumping = false;
item1[j].y = 0;
}
}
我尝试让 for 循环使用函数 19 次 (var i = 0; i <19; i++){ ...
,但在 It 项目之后根本没有跳跃。你有什么想法如何让我在完全跳跃后使用函数吗?
在我创建var j:Number = Math.round(Math.random()*5);
之后它在糟糕的情况下工作,因为它开始跳转第二项,直到第一个未完成跳转。
最佳答案
//whether or not the main guy is jumping
var mainJumping:Boolean = false;
//how quickly should the jump start off
var jumpSpeedLimit:int = 15;
//the current speed of the jump;
var jumpSpeed:Number = jumpSpeedLimit;
// we declare the variable that will hold the random number
var randomItem:Number;
// this function will select a random number and make the item corresponding
// to that number to jump. You call it once and it continues running.
function selectRandom():void
{
randomItem = Math.round(Math.random() * 5);
this.addEventListener(Event.ENTER_FRAME, updateItems);
}
function updateItems(e:Event):void {
if(!mainJumping){
//then start jumping
mainJumping = true;
jumpSpeed = jumpSpeedLimit*-1;
item1[randomItem].y += jumpSpeed;
} else {
//then continue jumping if already in the air
if(jumpSpeed < 0){
jumpSpeed *= 1 - jumpSpeedLimit/75;
if(jumpSpeed > -jumpSpeedLimit/5){
jumpSpeed *= -1;
}
}
if(jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit){
jumpSpeed *= 1 + jumpSpeedLimit/50;
}
item1.y += jumpSpeed;
//if main hits the floor, then stop jumping
//of course, we'll change this once we create the level
if(item1[randomItem].y <= 450){
mainJumping = false;
item1[randomItem].y = 0;
// after the item is finished jumping, we remove the listener
// and make it select another number. It is basically a loop.
this.removeEventListener(Event.ENTER_FRAME, updateItems);
selectRandom();
}
}
我只是复制/粘贴您的代码并进行了一些修改。我相信你在某个地方错过了一些花括号。除此之外,我们的想法是在 updateItems 方法之外声明一个变量,因此项目的数量不会在每一帧随机变化。希望这能解决您的问题。
关于javascript - Action Script 3. 检查数组是否有元素不跳转,然后跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22864319/