1

easyjs と box2d を使用して、互いに衝突するいくつかのオブジェクトを作成しました。次のコードを使用して、画面にボックスを作成します。

var b = new Box(400,0); // pass xPos and yPos
stage.addChild(b.view);

私のスクリプトのある時点で、ボックスが円と衝突し、それが発生すると、三角形がボックスに向かってトゥイーンする必要があります。だから箱の位置が必要!私Box.jsは次の機能を持っています:

function getX(){
    var xPos = this.body.GetPosition().x * SCALE;
    return xPos;
}

同じ関数を次の関数に置き換えました。

function getX(){
    return this.x;
}

どちらの関数も、私が使用するブラウザ コンソールに対して同じ値を返しますがconsole.log(b.getX);、これは未定義です。リターン関数でパラメーターを渡す必要がありますか、それとも関数の構造が正しくありませんか?

4

2 に答える 2

4

あなたはconsole.log(b.getX)、

まず、関数を実行するのではなく、その内容をログに記録します。次に、関数は var bのプロパティではありません。

// create the function.
b.getX = function()
{
 this.x;
};

// runs the command.
b.getX();

編集:

あなたが間違ったことを説明する Jsfiddle: http://jsfiddle.net/kychan/zsWpN/

編集2:

まず、「プロパティ」とは何かを説明します。プロパティは、特定のオブジェクトが所有する「もの」です。var を定義してインスタンス化しましょう。

var x = {}; // this makes an object.

プロパティを追加することもできます。

var y = {myProp1:'Hello', myProp2:'World'};

これにより、2 つのプロパティ (myProp1 と myProp2) を持つオブジェクト (y) が作成されます。

ここで、コード (jsfiddle) に (グローバル) 関数 getX があります。これはプロパティとして設定されていないため、グローバル ステートメントとして呼び出す必要があります。

getX(b); // should return this.x;

より完全な説明をいじる: http://jsfiddle.net/kychan/WwxC9/

//    METHOD 1 (Your method); works, but you can do it more directly, see METHOD 2.
//    define the var, with 'var'.
//    let it hold a (global) function.
var getX = function(object){
    return object.x;
};

//    we make a test variable holding an object with property x:
var foo = {x:4};
console.log(getX(foo)); // this should return 4.

//    METHOD 2:
//    we will make a normal function (which has the same execution as METHOD 1).
function getX2(o)
{
    return o.x;
}

//    create a test variable.
var bar = {x:4};
console.log(getX2(bar)); // should print 4 as well.

//   METHOD 3:
//    now we create a CLASS which has a default property named getX:
function myObject()
{
    this.x     = 4;

    //    here, this is called a method (because it is a property owned by a class/object).
    this.getX  = function()
    {
        return this.x;
    };
}

//    we create a test variable holding the object from the class myObject.
var baz = new myObject();
console.log(baz.getX()); // now it ALSO should print 4!
于 2014-04-20T15:48:36.487 に答える
1

カイの例と一緒に、私はついにそれを動かしました! だから、ありがとうカイ!ボックス関数の目盛り関数に変数を追加することで、彼が最終編集で示した 3 番目の方法を使用しました。これが私がしたことです:

Box.jsの場合は、box2d で b2_staticBody を作成し、ボックスの x 位置を返す getX 関数を指定しました。

this.getX = function(){
    return boxX;
}

私の tick 関数 (easeljs で作成) はボックスの位置を更新するので、ここでは box.x を boxX という var に保存します。

function tick(e){
    boX = this.body.GetPosition().x * SCALE;

    this.x = this.body.GetPosition().x * SCALE;
    this.y = this.body.GetPosition().y * SCALE;
    this.rotation = this.body.GetAngle() * (180/Math.PI);
}

b.getX();ボックスを作成した後、関数を呼び出すことができるようになりました。

b = new Box(350,450); // x and y position
stage.addChild(b.view);
var targetX = b.getX();
console.log(targetX);

私の問題に取り組む方法を理解し、プロパティなどを使用して理解するのを手伝ってくれたカイにもう一度感謝します.

于 2014-04-22T20:36:18.007 に答える