gpt4 book ai didi

java - 我将如何在 C# 中实现 java 代码,反之亦然?

转载 作者:行者123 更新时间:2023-12-02 01:34:31 24 4
gpt4 key购买 nike

我正在尝试统一创建一个游戏,但不能在其中使用 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);
}

关于java - 我将如何在 C# 中实现 java 代码,反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55426131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com