我正在尝试用Unity制作一个2D游戏,我在FixedUpdate()函数中使用了Input.GetMouseButtonDown()方法。我想让我的玩家改变水平方向,所以我有下面的代码。
if (Input.GetMouseButtonDown(0))
{
if(change == true)
{
rb.velocity = new Vector2(-12,rb.velocity.y);
change=!change;
}
else if(change == false)
{
change=!change;
rb.velocity = new Vector2(12,rb.velocity.y);
}
}在开始时,首先点击3-6次,效果很好(一次点击改变方向,另一次点击另一个方向),但之后我必须按2到3次才能改变实际方向。
我应该怎么做才能提高更改方向的准确性和质量?
非常感谢您的耐心和关注!
发布于 2019-07-31 20:53:07
Unity文档指出,您必须在更新函数中使用GetMouseButtonDown()。
您可能应该创建一个全局布尔值来保存该值并在FixedUpdate()中重置它。如下所示:
boolean MouseButtonDown=false;
void Update(){
if(Input.GetMouseButtonDown(0)){
MouseButtonDown=true;
}
}
void FixedUpdate(){
if (MouseButtonDown)
{
if(change == true)
{
rb.velocity = new Vector2(-12,rb.velocity.y);
change=!change;
}
else if(change == false)
{
change=!change;
rb.velocity = new Vector2(12,rb.velocity.y);
}
}
}发布于 2019-07-31 21:11:29
FixedUpdate()函数在一段固定的时间间隔后运行,如果您在执行if(Input.GetMouseButtonDown(0)时单击鼠标按钮,则您的输入将被考虑在内。对于屏幕上显示的每一帧,Update()函数都会运行,如果您的fps (帧速率)是60fps,这意味着Update()函数每秒运行60次,因此您的输入没有被记录的可能性非常低。希望这能解释为什么你的代码不能正常工作。
您可以做的是:
bool btnPressed = false;
void Update(){
if(Input.GetMouseButton(0) && !btnPressed){
btnPressed = true;
}
}
void FixedUpdate(){
if(btnPressed){
if(change == true){
rb.velocity = new Vector2(-12,rb.velocity.y);
change=!change;
}
else if(change == false){
change=!change;
rb.velocity = new Vector2(12,rb.velocity.y);
}
btnPressed = false;
}
}https://stackoverflow.com/questions/57291002
复制相似问题