java - 我将如何在 c# 中实现 java 代码,反之亦然?
问题描述
我正在尝试统一创建游戏,但无法在其中使用 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);
}
推荐阅读
- c - 我正在编写使用 ASCII 将小写字符转换为大写字符的 C 函数,但输出不正确
- c - zig 创建了一个 C 库,但 C 不能使用
- webstorm - Ctrl+Shift+Arrow 从 WebStorm 中消失了吗?
- webpack - html-webpack-plugin@4.5.0 和 html-loader@1.3.2
- java - 如何解决与用户定义的方法和对象相关的 Java 中的以下错误?
- laravel - Laravel Homestead 不接受密钥对
- html - 仅使用 HTML 垂直对齐段落
- android - 无法应用插件 [class 'org.gradle.language.base.plugins.LifecycleBasePlugin']
- excel-formula - 如何根据 Excel 中的另一列计算唯一值
- c++ - 编写一个主程序为空但打印“hello there!”的程序 屏幕上