簡體   English   中英

我將如何在C#中實現Java代碼,反之亦然?

[英]How would I go about implementing java code in c# and vice versa?

我試圖統一創建游戲,但是無法在其中使用Java,因此任何預制腳本都在C#中。 我想在游戲機制中添加一些內容,這需要我更改腳本中的變量和值,但是我只知道如何在Java中進行更改,因此我將如何使其能夠有效地進行交流?

來自c#的示例:

    protected override void ComputeVelocity()
{
    Vector2 move = Vector2.zero;

    move.x = Input.GetAxis ("Horizontal");
    if (Input.GetButtonDown ("Jump") && grounded) {
        velocity.y = jumpTakeOffSpeed;
    } else if (Input.GetButtonUp ("Jump"))
    {
        if (velocity.y > 0)
            velocity.y = velocity.y * .5f;
    }

    targetVelocity = move * maxSpeed;

}
}

和我的Java代碼:

public void keyPressed(KeyEvent e) 
{
    if(e.getKeyCode() == KeyEvent.VK_SHIFT)
    { 
        endTime = (System.currentTimeMillis() / 1000);
        timePassed = endTime - startTime; 
        if(timePassed >= 2)
        {   

            //try to set a time limit or something 

            velocity = overMaxVelocity;
            //set velocity to above usual max for dodgeTime 
            startTime = dodgeTime + (System.currentTimeMillis() / 1000);
        }


    }

}

我試圖做到這一點,所以當按下shift鍵時,速度會在短時間內更改為比平常大的值,但是我什至不知道從哪里開始

Unity僅支持用C#編寫的腳本。 它曾經還支持一個稱為UnityScript的JavaScript版本,但是現在它們僅遷移到正式支持C#。 幸運的是,C#與Java非常相似,因此將腳本轉換為C#不會有太多麻煩。 主要的挑戰是學習Unity庫。

我在下面編寫了一些代碼,這些代碼使用Unity庫函數來更新對象的速度。 Unity有很多內置的方法可以幫助您成為開發人員,因此我建議您在Unity網站上推薦教程,以獲取更多有關使用它的入門信息。

public float speed = 2;
public float speedUpFactor = 2;

// Get the Rigidbody component attached to this gameobject
// The rigidbody component is necessary for any object to use physics)
// This gameobject and any colliding gameobjects will also need collider components
Rigidbody rb;
// Start() gets called the first frame that this object is active (before Update)
public void Start(){
    // save a reference to the rigidbody on this object
    rb = GetComponent<Rigidbody>();
}
}// Update() gets called every frame, so you can check for input here.
public void Update() {

    // Input.GetAxis("...") uses input defined in the "Edit/Project Settings/Input" window in the Unity editor.
    // This will allow you to use the xbox 360 controllers by default, "wasd", and the arrow keys.
    // Input.GetAxis("...") returns a float between -1 and 1
    Vector3 moveForce = new Vector3(Input.GetAxis ("Horizontal"), 0, Input.GetAxis("Vertical"));
    moveForce *= speed;

    // Input.GetKey() returns true while the specified key is held down
    // Input.GetKeyDown() returns true during the frame the key is pressed down
    // Input.GetKeyUp() returns true during the frame the key is released
    if(Input.GetKey(KeyCode.Shift)) 
    {
        moveForce *= speedUpFactor;
    }
    // apply the moveForce to the object
    rb.AddForce(moveForce);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM