我正在尝试以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次更改实际方向。
我该怎么做才能提高方向的准确性,质量?
非常感谢您的耐心和关注!
Unity文档指出您必须在更新功能中使用getMouseButtondown((。
您可能应该创建一个全局布尔来保存值并将其重置在固定的update((中。这样的东西:
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);
}
}
}
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;
}
}