【问题标题】:How to make object move continously without stopping(unity2d)如何使物体连续移动而不停止(unity2d)
【发布时间】:2014-11-04 17:41:08
【问题描述】:

所以我在这里有这个脚本,当你点击它时,它会将播放器移动 -1.25,但我希望它不断添加 -1.25,直到你释放按钮。现在它只在您单击按钮时移动一次。我的代码:

var character : GameObject;
function OnMouseDown () {
    character.GetComponent(Animator).enabled = true;
    BlahBlah ();
}
function OnMouseUp () {
    character.GetComponent(Animator).enabled = false;
}

function BlahBlah () {
    character.transform.position.x = character.transform.position.x + -1.25;
}

有人有什么想法吗?谢谢!

【问题讨论】:

  • 也许有一个布尔值在鼠标按下时设置为真,在鼠标抬起时设置为假,然后将移动放入检查此布尔值的 while 循环中。

标签: unity3d unityscript


【解决方案1】:

您只是忘记在 Update() 中工作

var character : GameObject;
function OnMouseDown () 
{
    character.GetComponent(Animator).enabled = true;
}

function OnMouseUp () 
{
    character.GetComponent(Animator).enabled = false;
}

function BlahBlah () 
{
    // I added time.deltaTime, since you'll be updating the value every "frame",
    // and deltaTime refers to how much time passed from the last frame
    // this makes your movement indipendent from the frame rate
    character.transform.position.x = character.transform.position.x  - (1.25* time.deltaTime);
}

// The standard Unity3D Update method runs every frame
void Update() 
{
    if (character.GetComponent(Animator).enabled)
    {
        BlahBlah ();
    }
}

我在这里所做的是使用 Unity 逻辑。几乎所有东西都在 Update() 函数中工作,该函数在每一帧都被调用。请注意,帧速率可能会因机器/场景的复杂性而异,因此请确保在添加相关内容时始终使用 Time.deltaTime。

给您的另一个注意事项:直接修改位置不会使您的对象对碰撞做出反应(因此您将穿过对象,但您仍会“触发”碰撞)。所以,如果你想管理碰撞,记得使用物理!

【讨论】:

    【解决方案2】:

    您可以使用 Input.GetMouseButton,因为它会记录每一帧,所以当您按住鼠标时它会获取它,但因为它会检查每一个鼠标按下时的帧,因此您的对象将移动 如此快速,因此您可能需要添加一个 计时器,如果达到时间,它会移动,因此它会移动得慢一些,所以我们检查我们在 timeLeft 中设置的指定时间量是否通过并且鼠标按住然后我们移动我们的对象

       float timeLeft=0.5f; 
    
            void Update(){
              timeLeft -= Time.deltaTime;
            if (Input.GetMouseButton(0)){
                     if(timeLeft < 0)
                     {
                          BlahBlah ();
                     }
                }
            }
    
            void BlahBlah () {
                timeLeft=0.5f;
                character.transform.position.x = character.transform.position.x + -1.25;
            }
    

    【讨论】:

    • 在转换更改结束时不需要 *time.deltatime 吗?
    • 他想在一帧中移动他的对象,因为他的问题不在于移动它
    • 啊,是的,刚刚注意到他也没有,但仍然需要它!
    • 在更新功能中对移动使用 time.deltaTime 是一个很好的做法,但这不是强制性的,无论如何它都会起作用,尽管移动在其他设备上不会相同
    【解决方案3】:

    我记得 onMouseDown 会在您按住按钮时触发每一帧,因此您需要在该函数中进行移动,让我检查一下。

    【讨论】:

      猜你喜欢
      • 2017-08-04
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多