簡體   English   中英

Unity-為什么這僅在if語句內起作用

[英]Unity - Why does this only work inside the if statement

我在移動角色時遇到問題。

以下代碼有效。

        if (controller.isGrounded)
        {
            // X/Z Movement
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;
            // Y Movement.
            if (Input.GetButtonDown("Jump"))
                moveDirection.y = jumpForce;
        }
        // Apply gravity.
        moveDirection.y -= grav * Time.deltaTime;
        // Move the player.
        print(moveDirection);
        controller.Move(moveDirection * Time.deltaTime);

但是,如果我在if語句之前在X / Z Movement和Y Movement注釋之間移動所有內容,則播放器只會掉落少量,而不會隨着播放時間的延長而增加。 有人知道發生了什么嗎?

哎呀。 這是因為Im會在Update的每個循環中重置moveDirection.y,因此與其疊加重力,不如將其重置為0,然后應用-= grav * Time.deltatime

幾周前,我曾遇到過同樣的問題,我想我可以幫忙:您看到的實際“問題”來自這里:

moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

如果播放器接地,則沒有理由在Y軸上移動他,因此其值為0,但是如果將其移動到Update之外,它將繼續重置每一幀。

現在這行: moveDirection.y -= grav * Time.deltaTime; 從Vector3的Y減去0,而不是從moveDirection創建的moveVector的Y moveDirection.y = jumpForce;

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM