简体   繁体   English

按住 UI 按钮统一执行一个动作

[英]Hold down UI button to perform an action in unity

I'm making a simple game in unity, and I decided to make it able to be played on mobile, so to move a cube I use the AddForce method inside of the update method, but now I added two buttons to move the cube, but the problem is that I have to make the action on a hold function instead of click one, so how is that done in unity?我正在统一制作一个简单的游戏,我决定让它能够在移动设备上玩,所以要移动一个立方体,我在 update 方法中使用 AddForce 方法,但现在我添加了两个按钮来移动立方体,但问题是我必须暂停 function 而不是单击一个,那么如何统一完成? something like this but with a button hold...像这样的东西,但有一个按钮按住......

if (Input.GetKey("a") || Input.GetKey("[4]") || Input.GetKey("left"))
    {
        rb.AddForce(-sideWaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }

And I'm using Unity 2020.我正在使用 Unity 2020。

What you can do is you can add a rigidbody to the cube and make a script for the ui canvas.您可以做的是向立方体添加一个刚体并为 ui canvas 编写脚本。 Once you done that, you can reference the cube like this: public GameObject cube;完成后,您可以像这样引用立方体: public GameObject cube; . . Then in the update function what you can do is add some if statements checking if either button is pressed.然后在更新 function 中,您可以添加一些 if 语句检查是否按下了任一按钮。 And if for example the button that makes the cube move left is pressed, add a force to the cube on the x axis.例如,如果按下使立方体向左移动的按钮,则在 x 轴上向立方体添加一个力。 I can give you a hint on how to do this: cube.GetComponent<Rigidbody>().AddForce(15, 0, 0) .我可以给你一个提示: cube.GetComponent<Rigidbody>().AddForce(15, 0, 0) I'm sure you can figure the rest out by yourself.我相信您可以自己弄清楚 rest。

I hope you found this useful: :D我希望你觉得这很有用: :D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM