T
T
Triborg-3332022-02-23 04:55:55
Unity
Triborg-333, 2022-02-23 04:55:55

Protection against the intersection of generated objects - Unity 2d?

Hello, dear programmers) I can’t solve the problem, please help)
It is necessary to make sure that the created objects do not intersect (that is, do not overlap each other).

621594882bb50887444904.png

The code:

public GameObject player;
    public GameObject platformPrefab;
   
    public float minY = -4.5f;
    public float maxY = 4.7f;

    Vector2 spawnFix;

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Platform"))
        {
            Vector2 targetPosition = new Vector2(Random.Range(-1.8f, 1.8f), player.transform.position.y + Random.Range(4.5f, 4.7f));
            GameObject p = Instantiate(platformPrefab, targetPosition, Quaternion.identity);
            Destroy(collision.gameObject);
        }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2022-02-23
@GavriKos

Well, check after instancing - if it crossed - move / delete. What exactly is not working for you?
PS yes, my algorithm itself is shit, but you need to start small

A
AliminVerckon, 2022-02-23
@AliminVerckon

public GameObject player;
    public GameObject platformPrefab;
   
    public float minY = -4.5f;
    public float maxY = 4.7f;

public float ratio = 1.2f;
public float sizeplatformony;
public float lastvalue;

    Vector2 spawnFix;

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Platform"))
        {
           Value = player.transform.position.y + Random.Range(MinY MaxY);
            Vector2 targetPosition = new Vector2(Random.Range(-1.8f, 1.8f),  value);
if(Value-lastvalue > sizeplatformony + ratio){
            GameObject p = Instantiate(platformPrefab, targetPosition, Quaternion.identity);
            Destroy(collision.gameObject);
lastvalue = Value;
} else {
GameObject p = Instantiate(platformPrefab, targetPosition+ratio, Quaternion.identity);
            Destroy(collision.gameObject);
lastvalue = Value + ratio;
}
        }
    }

Not all code = bad, I don't know how you generate the first platform, but you will have to put the Y coordinate of the first platform in lastvalue, otherwise there will be a conflict!
You edit it carefully in the editor and if there are errors in the register, also in the IDE.
And ratio (Coefficient) you set up as you need in the inspector, it affects the minimum height between the new and old platform

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question