【问题标题】:Gameobject does not clamp but rather jitters游戏对象不钳位而是抖动
【发布时间】:2015-09-03 07:29:47
【问题描述】:

我试图将我的游戏对象的 y 值限制为 4 和 -4,但它一直跳到 ymax 和 ymin。我能想到的唯一原因是因为最后一行代码。我只是限制 y 值,因为 x 和 z 值在游戏中没有改变。游戏类似于乒乓球。

using UnityEngine;
using System.Collections;

public class Movement1 : MonoBehaviour 
{

public Vector3 Pos;
void Start () 
{
    Pos = gameObject.transform.localPosition;
}

public float yMin, yMax;
void Update () 
{
    if (Input.GetKey (KeyCode.W)) {
        transform.Translate (Vector3.up * Time.deltaTime * 10);
    }
    if (Input.GetKey (KeyCode.S)) {
        transform.Translate (Vector3.down * Time.deltaTime * 10);
    }

    Pos.y = Mathf.Clamp(Pos.y,yMin,yMax);
    gameObject.transform.localPosition = Pos;
}

}

【问题讨论】:

    标签: c# unity3d transform clamp jitter


    【解决方案1】:

    Pos.y 分配永远不会发生,因为您不能只更改 y 值;你必须制作一个新的 Vector3。请尝试以下操作:

    using UnityEngine;
    using System.Collections;
    
    public class Movement1 : MonoBehaviour 
    {
    
    public float yMin, yMax; // be sure to set these in the inspector
    void Update () 
    {
    
        if (Input.GetKey (KeyCode.W)) {
            transform.Translate (Vector3.up * Time.deltaTime * 10);
        }
        if (Input.GetKey (KeyCode.S)) {
            transform.Translate (Vector3.down * Time.deltaTime * 10);
    
        }
    
        float clampedY = Mathf.Clamp(transform.localPosition.y,yMin,yMax);
        transform.localPosition = new Vector3 (transform.localPosition.x, clampedY, transform.localPosition.z);
    
    }
    
    }
    

    【讨论】:

      【解决方案2】:

      您没有为yMinyMax 初始化任何值。

      另外,您应该为第二个Translate 加上else if,否则同时按下可能会导致抖动。

      但实际上,应该更像这样:

      using UnityEngine;
      using System.Collections;
      
      public class Movement1 : MonoBehaviour 
      {
          public Vector3 Pos;
          public float speed = 10f;
          public float yMin = 10f;
          public float yMax = 50f;
      
          void Update () 
          {
              Pos = gameObject.transform.localPosition;
      
              if (Input.GetKey (KeyCode.W))
                  Pos += (Vector3.up * Time.deltaTime * speed);
      
              if (Input.GetKey (KeyCode.S))
                  Pos += (Vector3.down * Time.deltaTime * speed);
      
              Pos.y = Mathf.Clamp(Pos.y,yMin,yMax);
              gameObject.transform.localPosition = Pos;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-16
        • 1970-01-01
        相关资源
        最近更新 更多