Haxe for循环仅使用最后一项

问题描述 投票:1回答:3

几个小时后做了一些测试,我发现我的地图包含正确的值,但我使用的循环似乎只是使用此地图中的最后一个添加值。我错过了一些明显的东西吗?

将项添加到地图的功能:(控件是地图变量)

public static function CreateThumbstick(mActorType:ActorType, mLocation:Int, mDirectionLock:Int)
    {
        var controllerName = "Thumbstick"+mLocation;
        if(!controls.exists(controllerName)){

            createRecycledActor(mActorType, 0, 0, Script.FRONT);
            var lastActor = getLastCreatedActor();
            var myPosition = GetPosition(controllerName, lastActor);
            lastActor.setX(myPosition.x);
            lastActor.setY(myPosition.y);
            var myPos = new Vector2(lastActor.getXCenter(), lastActor.getYCenter());            
            var controlUnit = new ControlUnit(lastActor, myPos, -1);
            controls.set(controllerName, controlUnit);

            trace("added key: " + controllerName +" with value: "+ lastActor);
        } else {
            trace("!!WARNING!! Control unit already exists in this position. Command ignored!");
        }
    }

在创建3个thumbsticks时,日志指出以下内容:

added key: Thumbstick1 with value: [Actor 1,Thumbstick]
added key: Thumbstick2 with value: [Actor 2,Thumbstick]
added key: Thumbstick3 with value: [Actor 3,Thumbstick]

当触摸屏幕时,它应该遍历我的地图中的每个项目,但它使用最后添加的项目3次来检查距离,而不是所有3个项目一次。这是触摸屏幕时调用的监听器:

addMultiTouchStartListener(function(event:TouchEvent, list:Array<Dynamic>):Void
        {
            for (unit in controls){
                trace(lastDebugLine + "checking distance to " + unit.GetActor());
                if(GetDistance(unit.GetCenter(), touch.GetPosition()) < 64){
                    break;
                }
            }
        });
// used "touch.GetPosition()" instead of actuall code for easy reading. This is not causing any problems!

触摸屏幕后,日志会指出以下内容:

checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]

我对Haxe语言很陌生,所以我的猜测是,即使在我非常密切地关注Haxe API之后,我也遗漏了一些明显的东西。这是Haxe API页面中使用的示例:

var map4 = ["M"=>"Monday", "T"=>"Tuesday"];    
for (value in map4) {
    trace(value); // Monday \n Tuesday
}

欢迎所有解释!

添加了ControlUnit类:

import com.stencyl.models.Actor;

class ControlUnit
{
    static var actor;
    static var center;
    static var touchID;

    public function new(mActor:Actor, mPosition:Vector2, mTouchID:Int) 
    {
        actor = mActor;
        center = mPosition;
        touchID = mTouchID;
    }

    public function GetActor():Actor{
        return(actor);
    }

    public function GetCenter():Vector2{
        return(center);
    }

    public function GetTouchID():Int{
        return(touchID);
    }
}
haxe stencyl
3个回答
3
投票

您只是在类定义中使用static作为变量 - 它们不是基于实例的/基于。在https://haxe.org/manual/class-field-property.html查看'属性',吸气剂,定位器等


1
投票

你确定getLastCreatedActor()每次都会返回一个单独的实例吗?如果每次你可能会看到你得到的东西,它会返回相同的实例。


1
投票

是不是因为你的所有键映射到相同的值?尝试将它们映射到不同的值并进行测试。

© www.soinside.com 2019 - 2024. All rights reserved.