【问题标题】:Do something when gameobject is on a specific position当游戏对象在特定位置时做某事
【发布时间】:2014-03-21 20:28:03
【问题描述】:

我正在尝试编写一个小游戏,其中游戏对象正在向前运行,直到它对着一个对象运行。当他与物体碰撞时,他正在向上移动。在一个特定的位置,我希望他再次向前跑。我试图请求类似:

if(posx == gameObject.transform.position.x && posy == gameObject.transform.position.y)
{
    setdirection1();
    update();
}

这是我当前的代码:

using UnityEngine;

public class MoveScript : MonoBehaviour
{
    // 1 - Designer variables

    /// <summary>
    /// Object speed
    /// </summary>
    public Vector2 speed = new Vector2(10, 10);
    public string tag = "Seil";    

    /// <summary>
    /// Moving direction
    /// </summary>
    public Vector2 direction = new Vector2(1, 0);

    private Vector2 movement;

    void Update()
    {
        // 2 - Movement
        movement = new Vector2(
            speed.x * direction.x,
            speed.y * direction.y);    


    }
    void setdirection()
    {
        Vector2 direction1 = new Vector2(0, 1);
        direction = direction1;
    }

    void setdirection1()
    {
        Vector2 direction2 = new Vector2(1, 0);
        direction = direction2;
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == tag)
        {            
            setdirection();
            Update(); 
        }


    }


    void FixedUpdate()
    {
        // Apply movement to the rigidbody
        rigidbody.velocity = movement;
    }
}

【问题讨论】:

  • 实际错误是什么?
  • 没有错误。我尝试了我在帖子顶部发布的示例,但没有成功。

标签: c# position unity3d transform


【解决方案1】:

You should never compare two floats with equality.

Unity 有 Mathf.Approximately 专门为此原因:

if (Mathf.Approximately(posx, gameObject.transform.position.x) && Mathf.Approximately(posy, gameObject.transform.position.y))
{
    setdirection1();
    update();
}

另外,根据Unity's documentation 对于Vector == Vector(强调我的):

如果向量相等,则返回 true。
对于非常接近相等的向量,这也将返回 true

因此,您可以这样做:

if (new Vector(posx, posy) == gameObject.transform.position))
{
    setdirection1();
    update();
}

在我看来,最安全的方法是设置阈值(听起来你有类似的东西):

if (gameObject.transform.position.x < posx ...)

if (gameObject.transform.position.x > posx ...)

【讨论】:

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