문제

I am trying to code a small game where a gameobject is running forward till it runs against a object. When he collide with the object he is moving upwards. At a specific position I want that he runs forward again. I tried to request something like:

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

This is my current code:

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;
    }
}
도움이 되었습니까?

해결책

You should never compare two floats with equality.

Unity has Mathf.Approximately specifically for that reason:

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

Also, according to Unity's documentation for Vector == Vector (emphasis mine):

Returns true if the vectors are equal.
This will also return true for vectors that are really close to being equal.

Thus, you can do:

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

In my opinion, the safest way would be to have thresholds (and it sounds like you have something similar):

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

or

if (gameObject.transform.position.x > posx ...)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top